简体   繁体   中英

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. 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,

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:

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] . This result is stored back in column 923

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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