-2

currently, I am using for loops for sum of rows like below

dat <- c(1,2,3,4)
dat1 <- c(1,2,3,4)
dat2 <-c(1,2,3,4)

df <- data.frame(dat,dat1,dat2)


sum <- NULL
for (i in 1:nrow(df)){
  i <- sum(df[i,],na.rm=T)
  sum <- rbind(sum,i)

what would be the fastest way to do this, keeping the structure same as my example sum

AlgoQuant
  • 63
  • 6

1 Answers1

2

We can use rowSums which would be much faster than the looping through the rows as rowSums is vectorized optimized for these kind of operations

matrix(rowSums(df, na.rm = TRUE))
akrun
  • 874,273
  • 37
  • 540
  • 662