[R]这个带有多个ifs的for循环可以被矢量化吗?

时间:2016-11-04 14:48:07

标签: r

[noob alert]我刚学了一些关于向量化及其在R中的代码运行时间的影响,所以我想到如果可能的话尝试对我的旧代码进行矢量化。 我有一个使用多个IF的for循环,结果很慢。这可以被矢量化吗?

for(i in 1:nrow(merge24)){
  if(is.na(merge24$Paid.Avg.x[i]) & is.na(merge24$Paid.Avg.y[i])){
    merge24$Tot.Paid.Avg[i] = NA
  }
  else if(is.na(merge24$Paid.Avg.x[i])){
    merge24$Tot.Paid.Avg[i] = merge24$Paid.Avg.y[i]
  }
  else if(is.na(merge24$Paid.Avg.y[i])) {
    merge24$Tot.Paid.Avg[i] = merge24$Paid.Avg.x[i]
  }
  else {
    merge24$Tot.Paid.Avg[i] = (merge24$Paid.Avg.y[i] +merge24$Paid.Avg.x[i])/2
  }
}

1 个答案:

答案 0 :(得分:1)

皮埃尔用data.table

merge24 <- data.table(merge24)
merge24[, .(Paid.Avg.Tot = rowMeans(.SD, na.rm=TRUE)), .SDcols = c("Paid.Avg.x", "Paid.Avg.y")]