[R] sum sections of data of different lengths from within a data frame

Kara Przeczek przeczek at unbc.ca
Wed Feb 10 03:06:40 CET 2010


Dear R Help:

I am trying to sum data from one column in a dataframe based on a value in another. I do not know how to do this easily in R.
For example:

Col A  Col B
1        0
3        0
2        1
2        0
1        0
4        0
1        1
9        1
3        0
5        0
2        1

I would like to cumsum the values in Col A for all rows where Col B is 0, and a value of 1 in Col B will reset the sum and give a value of 0.001. Thus, for this table I would like an output of 1, 4, 0.001, 2, 3, 7, 0.001, 0.001, 3, 8, 0.001.
I tried using a For loop, but that summed all the Col A values together. I need something that does
For (i in 1:length(df$Col B))
{
IF{Col B == 0, cumsum(Col A) "until" Col B == 1, else 0.001}
}
I don't know how to use "until" in R.
Any help would be greatly appreciated!
Kara



More information about the R-help mailing list