R中零点之间向量的总和 [英] Sum elements of a vector beween zeros in R

查看:25
本文介绍了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.

因此,我想要的输出是:13815614.

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 

<小时>

我们也可以使用 sapplysplit

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

这篇关于R中零点之间向量的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆