Paul
Paul

Reputation: 11

Create a column with the aggregated values of another column in R

I have a column of values and want to create another column with the aggregated values of the first column.

df <- c(x = 0, y = 0)
df$x <- c(1:5)
df$y <- df$x + lag(df$y, default = 0)
> df
$x
[1] 1 2 3 4 5

$y
[1] 1 2 3 4 5

My expectation is that the value of y equals: 1 3 6 10 15. What do I do wrong ?

Upvotes: 0

Views: 30

Answers (1)

akrun
akrun

Reputation: 887078

We may need cumsum

df$y <- cumsum(df$x)

Or accumulate

library(purrr)
accumulate(df$x, `+`)
[1]  1  3  6 10 15

Upvotes: 1

Related Questions