数据
考虑您具有以下data.table或dataframe(我正在使用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
a 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
问题
我试图将第一行的X3和X4求和,第二行的X3和X4和X5求和,等等。
我做了什么
我有一个称为iter的向量:
iter <- c(1,2,3,4)
我所做的是一个for循环
for(i in 1:nrow(df)){
df$sum[i] <- sum(as.numeric(df[i,2:(2+iter[i])]),na.rm=T)}
您知道没有for循环的方法吗?
预期产量
output
13.7 #correspond to df[1,X3]+df[1,X4]
13.4 #correspond to df[2,X3]+df[2,X4]+df[2,X5]
27.4 #correspond to df[3,X3]+df[3,X4]+df[3,X5]+df[3,X6]
37.4 #correspond to df[4,X3]+df[4,X4]+df[4,X5]+df[4,X6]+df[4,X7]
编辑
iter <- c(1,2,3,4)
在这里是完全任意的,所以我需要一个针对iter值的解决方案
您可以将其Reduce
与accumulate = TRUE一起使用,然后提取值。
# initialize iter variable
iter <- 1:4
# calculate cumulative row sums, dropping initial list element
vals <- Reduce("+", df[2:10], accumulate=TRUE)[-1]
# pull out what you want with recursive indexing and sapply
sapply(1:nrow(df), function(x) vals[[c(iter[x], x)]])
[1] 13.7 13.4 27.4 34.7
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句