[英]Apply sum to chunks of a vector in R?
I have a vector v
containing the number of elements I need to add up from another vector w
. 我有一个向量v
其中包含需要从另一个向量w
的元素数量。 How can I do this in R? 我如何在R中做到这一点?
Example 例
v = c(4,0,3,3,0,0)
w = rexp(10,1)
So, I need a new vector containing c(w[1]+w[2]+w[3]+w[4],0,w[5]+w[6]+w[7],w[8]+w[9]+w[10],0,0)
. 因此,我需要一个包含c(w[1]+w[2]+w[3]+w[4],0,w[5]+w[6]+w[7],w[8]+w[9]+w[10],0,0)
。 How can I construct such vector? 如何构建这样的载体? I thought of using apply
but I cannot see how to do it. 我曾考虑过使用apply
但看不到该怎么做。 A for
loop could also work, but there is a problem with the zeroes. for
循环也可以工作,但是零有问题。
We can use rep
on the sequence of 'v' to create a grouping variable, get the sum
of 'w' with tapply
using the grouping variable and append the 0's based on the position of '0' in 'v' 我们可以对``v''的序列使用rep
来创建分组变量,使用分组变量tapply
以获取``w''的sum
,并根据``v''中的``0''的位置附加0
r1 <- unname(tapply(w, rep(seq_along(v), v), FUN = sum))
i1 <- which(v==0)-1
for(i in seq_along(i1)) r1 <- append(r1, 0, after = i1[i])
r1
#[1] 2.951259 0.000000 2.982644 4.233564 0.000000 0.000000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.