R 中零点之间向量的总和元素 [英] Sum elements of a vector beween zeros in R
问题描述
我有一个带有零和正数的向量.我只想对介于零之间的数字求和.
I have a vector with zeros and positives numbers. I would simply like to sum the numbers that are between the zeros.
一个简单的例子:
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)
也就是说,我想对元素 1,23,24,54,12,1,23
, 1,23,56,76
和 求和>1,13
.
That is, I want to sum the elements 1,23,24,54,12,1,23
, 1,23,56,76
and 1,13
.
因此,我想要的输出是:138
、156
和 14
.
My desired output would therefore be:
138
, 156
and 14
.
我发现了这个非常相似的问题,但它是在 Python 上的:Python 中零之间的列表元素求和
I found this really similar question but it is on Python: Sum elements of a list between zeros in Python
谢谢.
推荐答案
我们可以使用tapply
,用cumsum
创建组并取sum
每组.
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
由于所有数字都是正数,我们可以忽略带有 0 的数字并过滤值大于 0 的数字.
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
<小时>
我们也可以用 sapply
和 split
sapply(split(x, cumsum(x==0)), sum)
这篇关于R 中零点之间向量的总和元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!