求和,直到达到给定值 [英] Sum until a given value is reached

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

问题描述

所以我想我在这里对我的问题有了答案:

So I thought I had the answer to my question here: Cumulative sum until maximum reached, then repeat from zero in the next row but in fact it's not.

我想做的是能够对一列求和,直到在另一列中达到给定值为止.以我们为例:

What I would like to do is be able to sum a column until a given value is reached in another column. If we take for instance:

Col1   Col2   Col3   
 0      12     
 0      14
 1      2
 2      0.5
 1      12
 4      3
 3      2

我希望能够对第2列的所有值求和,直到在第1列达到4.这将是:12 + 14 + 2 + 0.5 + 12

I'd like to be able to sum all the values of column 2 until we reach 4 in column 1. This would give here: 12+14+2+0.5+12

我对R完全陌生,我对此一无所知.

I'm completely new to R and I sincerely have no idea on how to proceed.

我所拥有的是来自csv文件的数据帧:

What I have is a data frame from a csv file:

mydata = read.csv("mycsv.csv")

推荐答案

您可以使用cumsum(mydata$Col1 == 4) == 0来获取在Col1中是否达到4的逻辑向量.然后,您可以使用简单的索引从Col2中获取相关元素:

You can use cumsum(mydata$Col1 == 4) == 0 to get a logical vector of whether or not 4 has been reached in Col1. Then you can use simple indexing to grab the relevant elements from Col2:

sum(mydata$Col2[cumsum(mydata$Col1 == 4) == 0])
# [1] 40.5

这篇关于求和,直到达到给定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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