Search code examples
rfunctionseqrep

Adding rows and applying it to a data frame in R


I have a df:

Q1_3  Q2_3  Q3_3  Q4_3  Q5_3 ...  
16.01  8.23 18.13 11.14 18.03 ...  
17.25  7.50 11.72 10.84  7.24 ...  
3.08  2.12  4.39  3.16  2.44 ...    
4.94  3.95  6.87  3.75  4.10 ...  
3.89  8.35  7.80  2.90  2.55 ...  

I'd like to create a function that sequentially adds the df[1:5], [6:10] etc. and applies this to the whole data frame.

fun1<- function(x) c(x[1] + x[2], x[3] + x[4], x[5] + x[6], x[7] + x[8], x[9] + x[10], x[11] + x[12], x[13] + x[14]) 

I used this one to do another one that I need, however I think there should be a way to use seq() or rep() and apply it to the whole df.

testfun<- function(x) c(rowSums(x[1:5])) 

this adds up the columns that I need, however I cannot figure out how to sequence it for the whole df. I would appreciate your help.

Thanks


Solution

  • We can loop over the sequence (seq(1, ncol(df1), by =5)) , create the index (i:(i+4)), subset the dataset, do the rowSums and then cbind with the original dataset.

    cbind(df1, sapply(seq(1, ncol(df1), by=5), function(i)
                    rowSums(df1[i:pmin((i+4), ncol(df1))], na.rm=TRUE)))
    

    If we need a function

    f1 <- function(dat, n=5){
           cbind(dat, sapply(seq(1, ncol(dat), by = n), function(i)
                 rowSums(dat[i:pmin((i+(n-1)), ncol(dat))], 
                   na.rm=TRUE)))
           }
    f1(df1)