How to add cells based off of a specific integer?

Viewed 40

I want to add values from a column. They go in sequence:

0,225,2352,34234,23442,23456,0,123,...

I want to add the values from 0 until the following 0 but not including the second. For example, i want an output of (0+225+2352+34234+23442+23456),(0+123+,...,),...

I want to store them as a new column of totals

1 Answers

One simple solution in base R is

sapply(split(x, cumsum(x == 0)), sum)

With split you basically create groups of elements that you want to sum together using sapply. The final result will be a named numeric vector.


Sample data

x <- c(0,225,2352,34234,23442,23456,0,123,2,0,1,42)
sapply(split(x, cumsum(x == 0)), sum)
#     1     2     3  
# 83709   125    43
Related