R. Sum over rows

36 views Asked by At

Suppose in R we have a following starting "df" table.

names <- rep(c("Paul", "Marc", "Richard"), each = 20)
income <- sample(1:100, 60, replace = TRUE)
df <- data.frame(Name = names, Income = income, Contributions = contributions)

enter image description here

In this table I need to create a second column, lets say Wealth that is defined at each row, for each Name as the sum of initial income (initial row for the Name) plus the corresponding income at the i-th row. So for Paul, using the sample image as the reference, the Wealth at row 1 is 55, at row 2 is 55+38, at row 3 is 55+1. Yes it's counterintuitive, but I dont't need a cumulative sum. I couldn't came up with a better example. Same thing for Marc and Richard.

Thank you!

1

There are 1 answers

0
ThomasIsCoding On

With base R, you can use ave to have operations grouped by Name, e.g.,

transform(df, Wealth = ave(Income, Name, FUN = \(x) x[1]+c(0,x[-1])))