问题
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