Sum elements of a vector beween zeros in R

╄→гoц情女王★ 提交于 2020-11-29 09:48:08

问题


I have a vector with zeros and positives numbers. I would simply like to sum the numbers that are between the zeros.

A simple example:

x <- c(0,0,0,0,0,1,23,24,54,12,1,23,0,0,0,0,1,23,56,76,0,1,13)

That is, I want to sum the elements 1,23,24,54,12,1,23 , 1,23,56,76 and 1,13.

My desired output would therefore be: 138, 156 and 14.

I found this really similar question but it is on Python: Sum elements of a list between zeros in Python

Thanks.


回答1:


We can use tapply, creating groups with cumsum and take sum of each group.

new_x <- tapply(x, cumsum(x == 0), sum)
new_x

#  1   2   3   4   5   6   7   8   9  10 
#  0   0   0   0 138   0   0   0 156  14 

Since all numbers are positive we can ignore the ones with 0 and filter the one which has value greater than 0.

new_x[new_x > 0]
#  5   9  10 
#138 156  14 

We can also follow the same logic with sapply and split

sapply(split(x, cumsum(x==0)), sum)



回答2:


Here is a solution with data.table:

library("data.table")
x <- c(0,0,0,0,0,1,23,24,54,12,1,23,0,0,0,0,1,23,56,76,0,1,13)
s <- tapply(x, rleidv(x==0), sum)
s[s!=0]
# > s[s!=0]
#   2   4   6 
# 138 156  14 



回答3:


Not very compact, but also does it. Use which and diff to locate positions in x where value changed from non-zero to zero. Use that info to sum relevant sub-vectors.

z <- which(x!=0)[diff(which(x!=0))>1] # 12 20
z <- c(1, z, length(x))+1 # 2 13 21 24
for(i in 1:(length(z)-1)){ print(sum(x[z[i]:z[i+1]], na.rm=T)) }

[1] 138
[1] 156
[1] 14


来源:https://stackoverflow.com/questions/51963686/sum-elements-of-a-vector-beween-zeros-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!