简体   繁体   English

使R中的循环更快而不会并行化

[英]make for loop faster in R without parallalizing

I have the following very simple loop operation where I need to loop from 1 to 50,000. 我有以下非常简单的循环操作,需要从1循环到50,000。 Although the loop is very simple, itàs very slow in R, so I'm wondering if there is any operation can do to make it faster, but I don't prefer parallel solution since my computer has only 2 processors, 尽管循环非常简单,但R的运行速度却很慢,所以我想知道是否有任何操作可以使循环更快,但是我不喜欢并行解决方案,因为我的计算机只有2个处理器,

full3 = fullData
for(i in 1:dim(fullData)[1]) {
  full3[i,923] <- sum(as.numeric(full3[i, 879:912]))
  print(i)
}

You should use the vectorised rowSums operation for this: 您应该rowSums使用rowSums操作:

full3 <- fullData
# a[, b] selects the entire column 'b' from data.frame 'a'
full3[, 923] <- rowSums(as.numeric(full3[, 879:912]))

should do it. 应该这样做。 rowSums , well, calculates the sum of each row of the subset'd data.frame full3[, 879:912] . rowSums同样会计算子集的数据的每一行的总和data.frame full3[, 879:912] This result is stored back in column 923 该结果存储在列923中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM