我要计算第一个值到第十号的平均值,然后计算第十一到十五号的平均值,然后计算第十六到十八号的平均值,等等。基本上,我想要计算X值的平均值,其中X是在向量中给出的不同值。例如:
y=c(1,1,2,3,2,1,4,5,3,6,7,5,6,7,8,4,2,4)
x=c(10,5,3)然后,第一、第二和第三种手段是:
sum(1+1+2+3+2+1+4+5+3+6)/10
sum(7+5+6+7+8)/5
sum(4+2+4)/3你能帮帮我吗?谢谢!
发布于 2017-11-22 05:09:17
x <- cumsum(x)
x <- c(1,x)
for(i in 1:(length(x)+1)){
print(mean(y[x[i-]:x[i+1]]))发布于 2017-11-22 05:19:28
您可以从splitAt中借用this answer函数
splitAt <- function(x, pos) {
unname(split(x, cumsum(seq_along(x) %in% pos)))
}要拆分y,您需要从1开始,并将1添加到x中值的累积和中
splitAt(y, c(1, cumsum(x)+1))
[[1]]
[1] 1 1 2 3 2 1 4 5 3 6
[[2]]
[1] 7 5 6 7 8
[[3]]
[1] 4 2 4现在您有了一个列表,所以您可以使用lapply或sapply
sapply(splitAt(y, c(1, cumsum(x)+1)), mean)
[1] 2.800000 6.600000 3.333333https://stackoverflow.com/questions/47426971
复制相似问题