简体   繁体   中英

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

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) 
 n <- 5
 g <- as.numeric(gl(ncol(df1), n, ncol(df1)))
 e2 <- t(aggregate(t(as.matrix(df1))~ g, FUN=sum)[,-1])
 cbind(df1, e2)

1. construct a factor to group the columns.
2. aggregate the transposed dataframe
3. cbind()

and a little bit shorter:

n <- 5
g <- as.numeric(gl(ncol(df1), n, ncol(df1)))
e2 <- aggregate(t(df1)~ g, FUN=sum)
cbind(df1, t(e2[-1]))

as function:

f <- function(df, n=5) {
    g <- as.numeric(gl(ncol(df), n, ncol(df)))
    aggregate(t(df)~ g, FUN=sum)
}
cbind(df1, t(f(df1)[-1]))

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