【问题标题】:Trying to sum different columns number at the same time试图同时对不同的列数求和
【发布时间】:2017-08-18 13:17:50
【问题描述】:

数据

假设你有这个 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 值的解决方案

【问题讨论】:

  • @lmo 现在试试我编辑了数据框和 for 循环

标签: r for-loop dataframe data.table


【解决方案1】:

您可以将Reduce 与累加=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

【讨论】:

  • 这里一样,如果我想和 iter
  • 很简单的改变,我猜只要你想要累积和。我在递归索引中用c(iter[x], x) 交换了c(x, x)
  • reduce 可以处理NA 吗?
  • "+" 无法处理 NA。不过,您可以事先进行一些操作以将 NA 转换为 0。
【解决方案2】:

df 的元素是使解决方案有点复杂的因素。首先,我将相关列转换为数值矩阵。

编辑:更新版本的df 没有因素

mat <- sapply(df[,-1], as.numeric)
rowSums(mat*cbind(TRUE, lower.tri(mat[,-1], diag = TRUE)))

[1] 13.7 13.4 27.4 34.7

使用任意迭代器:

index.mat = t(sapply(iter, function(x){rep(c(TRUE,FALSE), times = c(x+1, ncol(df)-x))}))
rowSums(df[,-1]*index.mat)

20.2 38.5 34.6 27.9

【讨论】:

  • 糟糕,还有一件事,这里的对角线是任意的,如果我想和iter &lt;- c(2,5,4,3) 相加,它似乎不起作用
【解决方案3】:

这个呢? 如果 iter 指定列数:

iter <- c(2,5,4,2)
  sapply(1: length(iter),(function(i){
    ri <- iter[i]
      sum(df[i, 3:(3+ri-1)])
  }))

如果您将它用于行的顺序(例如,用于重新排序数据框中的行)

iter <- c(1,2,3,4)
sapply(1: length(iter),(function(i){
  ri <- iter[i]
    sum(df[ri, 3:(3+i)])
}))

【讨论】:

    猜你喜欢
    • 2013-08-15
    • 2018-04-12
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多