求和,直到达到给定值

问题描述:

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

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