添加行并将其应用于 R 中的数据框

Adding rows and applying it to a data frame in R

我有一个 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 ...  

我想创建一个按顺序添加 df[1:5]、[6:10] 等的函数,并将其应用于整个数据框。

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]) 

我用这个来做我需要的另一个,但是我认为应该有一种方法可以使用 seq() 或 rep() 并将其应用于整个 df。

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

这加起来了我需要的列,但是我不知道如何为整个 df 排序。非常感谢您的帮助。

谢谢

我们可以遍历序列 (seq(1, ncol(df1), by =5)),创建索引 (i:(i+4)),对数据集进行子集化,执行 rowSums 然后 cbind原始数据集。

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

如果我们需要一个函数

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。构造一个因子来对列进行分组。
2.聚合转置数据帧
3.cbind()

短一点:

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

作为函数:

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]))