[R] Running Total

Mikhail Titov mlt at gmx.us
Mon Mar 5 20:04:38 CET 2012


Edward Patzelt <patze003 at umn.edu> writes:

> Actually in looking at this I need it to only add if a 0 occurs instead of
> a 1.

cumsum(1-x)

>
> On Mon, Mar 5, 2012 at 12:57 PM, jim holtman <jholtman at gmail.com> wrote:
>
>> cumsum
>>
>> is probably what you want:
>>
>> > x <- c(1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 0L, 1L, 1L, 1L, 1L,
>> + 1L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L,
>> + 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L,
>> + 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L,
>> + 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L,
>> + 0L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L,
>> + 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L,
>> + 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L)
>> > cbind(x, cumsum(x))
>>       x
>>  [1,] 1   1
>>  [2,] 1   2
>>  [3,] 0   2
>>  [4,] 1   3
>>  [5,] 1   4
>>  [6,] 1   5
>>  [7,] 1   6
>>  [8,] 1   7
>>  [9,] 0   7
>>  [10,] 1   8
>>  [11,] 0   8
>>  [12,] 1   9
>>  [13,] 1  10
>>  [14,] 1  11
>>  [15,] 1  12
>>  [16,] 1  13
>>  [17,] 0  13
>>
>>
>> On Mon, Mar 5, 2012 at 1:51 PM, Edward Patzelt <patze003 at umn.edu> wrote:
>> > I'm am trying to create a vector that has a running total that adds each
>> > time a 1 occurs.  here's the code and data
>> >
>> > c(1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 0L, 1L, 1L, 1L, 1L,
>> > 1L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L,
>> > 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L,
>> > 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L,
>> > 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 1L,
>> > 0L, 1L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L,
>> > 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L,
>> > 0L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L)
>> >
>> >
>> > total <- {};
>> >
>> > for(i in 1:length(dat$Valid)){
>> > total[i] <- ifelse(dat$Valid[i-1]==1, total[i] + 1, total[i])
>> > }
>> >
>> >
>> > Cheers,
>> >
>> >
>> >
>> > --
>> > Edward H. Patzelt
>> > Research Assistant – TRiCAM Lab
>> > University of Minnesota – Psychology/Psychiatry
>> > VA Medical Center
>> > S355 Elliot Hall: 612-626-0072
>> > www.psych.umn.edu/research/tricam
>> >
>> >        [[alternative HTML version deleted]]
>> >
>> >
>> > ______________________________________________
>> > R-help at r-project.org mailing list
>> > https://stat.ethz.ch/mailman/listinfo/r-help
>> > PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> > and provide commented, minimal, self-contained, reproducible code.
>> >
>>
>>
>>
>> --
>> Jim Holtman
>> Data Munger Guru
>>
>> What is the problem that you are trying to solve?
>> Tell me what you want to do, not how you want to do it.
>>

-- 
Mikhail



More information about the R-help mailing list