r - Trying to sum different columns number at the same time -


data

consider have data.table or dataframe (i'm working data.table):

a <- c(1, 6.7, 7.0, 6.5, 7.0, 7.2, 4.2, 5, 6.6,6.7)  b <- c(2,5.0, 3.5, 4.9, 7.8, 9.3, 8.0, 7.8, 8.0,10) c <- c(3, 7.0, 5.5, 7.2, 7.7, 7.2, 8.0, 7.6, 7,6.7)  d <- c(4, 7.0, 7.0, 7.0, 6.9, 6.8, 9.0, 6.0, 6.6,6.7)  df <- data.frame(rbind(a,b,c,d))    x1  x2  x3  x4  x5  x6  x7  x8  x9  x10  1 6.7 7.0 6.5 7.0 7.2 4.2 5.0 6.6  6.7 b  2 5.0 3.5 4.9 7.8 9.3 8.0 7.8 8.0 10.0 c  3 7.0 5.5 7.2 7.7 7.2 8.0 7.6 7.0  6.7 d  4 7.0 7.0 7.0 6.9 6.8 9.0 6.0 6.6  6.7 

problem

i'm trying sum x3 , x4 first line, x3 , x4 , x5 second, etc...

what did

i have vector called iter :

iter <- c(1,2,3,4) 

and did loop

for(i in 1:nrow(df)){ df$sum[i] <- sum(as.numeric(df[i,2:(2+iter[i])]),na.rm=t)} 

do know way without loop ?

expected output

output     13.7  #correspond df[1,x3]+df[1,x4]    13.4  #correspond df[2,x3]+df[2,x4]+df[2,x5]    27.4  #correspond df[3,x3]+df[3,x4]+df[3,x5]+df[3,x6]    37.4  #correspond df[4,x3]+df[4,x4]+df[4,x5]+df[4,x6]+df[4,x7] 

edit

iter <- c(1,2,3,4) 

is arbitrary here, need solution value of iter

you can use reduce accumulate=true , extract values.

# initialize iter variable iter <- 1:4  # calculate cumulative row sums, dropping initial list element vals <- reduce("+", df[2:10], accumulate=true)[-1]  # pull out want recursive indexing , sapply sapply(1:nrow(df), function(x) vals[[c(iter[x], x)]]) [1] 13.7 13.4 27.4 34.7 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -