分割向量并求和 [英] Split a vector and summing values

查看:82
本文介绍了分割向量并求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R新手。我有一个向量

I'm a R newbie. I've got a vector

vec <- c(105,29,41,70,77,0,56,49,63,0,105)

我想对值求和,直到出现 0,然后创建具有以下值的向量,例如:

and i would like to sum values till "0" occurs and then create a vector with such values, such as:

vec2 <- c(322,168,105)

但是我真的不知道从哪里开始!有建议吗?

But i really don't know where to start! Any suggestion?

推荐答案

从此向量开始...

> vec
 [1] 105  29  41  70  77   0  56  49  63   0 105

我们可以计算零的逻辑TRUE / FALSE向量:

We can compute a logical TRUE/FALSE vector of where the zeroes are:

> vec == 0
 [1] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE

当您将FALSE和TRUE相加时,FALSE为零,而TRUE为1,因此,如果我们每次将向量相加就等于TRUE,则值会增加。因此,使用 cumsum 作为累计金额,我们得到:

When you add FALSE and TRUE, FALSE is zero and TRUE is one, so if we add that vector up every time we get to a TRUE the value increases. So using cumsum for the cumulative sum, we get:

> cumsum(vec==0)
 [1] 0 0 0 0 0 1 1 1 1 2 2

现在,结果定义了我们要添加到其中的组,因此让我们 split vec 结果:

Now that result defines the groups that we want to add up within, so let's split vec by that result:

> split(vec, cumsum(vec==0))
$`0`
[1] 105  29  41  70  77

$`1`
[1]  0 56 49 63

$`2`
[1]   0 105

因此,除了列表第二部分和后续部分中的零外,这就是我们要累加的数字。因为我们要添加,所以可以添加零,并且没有任何区别(但是,如果您想要平均值,则必须删除零)。现在,我们使用 sapply 遍历列表元素并计算总和:

So apart from the zeroes in the second and subsequent parts of the list, that's the numbers we want to add up. Because we are adding we can add the zeroes and it doesn't make any difference (but if you wanted the mean you would have to drop the zeroes). Now we use sapply to iterate over list elements and compute the sum:

> sapply(split(vec, cumsum(vec==0)),sum)
  0   1   2 
322 168 105 

工作完成。忽略 0 1 2 标签。

这篇关于分割向量并求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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