Sum up with the next line into a new colum

Hello guys, I'm having some trouble on figuring out how to create a new column with the sum of 2 subsequents cell.

supose I have df1<- tibble(Years=c(1990, 2000, 2010, 2020, 2030, 2050, 2060, 2070, 2080),
Values=c(1,2,3,4,5,6,7,8,9 ))

Now, I want a new column where the first line is the sum of 1+2, the second line is the sum of 1+2+3 , the third line is the sum 1+2+3+4 and so on.

As 1, 2, 3, 4... are hipoteticall values, I need to measure the absolute growth from a decade to another in order to create later on a new variable to measure the percentage change from a decade to another.

I hope I made sense.

Thanks in advance for any help.

Hi,

Welcome to the RStudio community!

library(tidyverse)
df1 <- tibble(Years=c(1990, 2000, 2010, 2020, 2030, 2050, 2060, 2070, 2080),
             Values=c(1,2,3,4,5,6,7,8,9 ))

df1 = df1  %>% mutate(cumsum = cumsum(df1$Values))
df1
#> # A tibble: 9 x 3
#>   Years Values cumsum
#>   <dbl>  <dbl>  <dbl>
#> 1  1990      1      1
#> 2  2000      2      3
#> 3  2010      3      6
#> 4  2020      4     10
#> 5  2030      5     15
#> 6  2050      6     21
#> 7  2060      7     28
#> 8  2070      8     36
#> 9  2080      9     45

Created on 2021-08-12 by the reprex package (v2.0.0)

Hope this helps,
PJ

1 Like

Thanks a lot. You're a time saviour.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.