Referencing specific columns and current values to sum rows?

Hello, I want to sum test column based on the test wt and values of previous values.
for example:


df <- mtcars %>% 
  select(mpg,wt) %>% 
  mutate(test = 0) %>% 
  head()

df[1,3] <- df[1,2]
df[2,3] <- df[2,2] + df[1,3]
df[3,3] <- df[3,2] + df[2,3]
df[4,3] <- df[4,2] + df[3,3]
df[5,3] <- df[5,2] + df[4,3]
df[6,3] <- df[6,2] + df[5,3]
suppressPackageStartupMessages({
  library(dplyr)
  })

# avoid df and other built in names; not a problem in this case
# but it can be mistaken for a closure in some contexts

my_df <- mtcars %>% 
  select(mpg,wt) %>% 
  mutate(test = lag(wt,1) + wt)

my_df
#>     mpg    wt   test
#> 1  21.0 2.620     NA
#> 2  21.0 2.875  5.495
#> 3  22.8 2.320  5.195
#> 4  21.4 3.215  5.535
#> 5  18.7 3.440  6.655
#> 6  18.1 3.460  6.900
#> 7  14.3 3.570  7.030
#> 8  24.4 3.190  6.760
#> 9  22.8 3.150  6.340
#> 10 19.2 3.440  6.590
#> 11 17.8 3.440  6.880
#> 12 16.4 4.070  7.510
#> 13 17.3 3.730  7.800
#> 14 15.2 3.780  7.510
#> 15 10.4 5.250  9.030
#> 16 10.4 5.424 10.674
#> 17 14.7 5.345 10.769
#> 18 32.4 2.200  7.545
#> 19 30.4 1.615  3.815
#> 20 33.9 1.835  3.450
#> 21 21.5 2.465  4.300
#> 22 15.5 3.520  5.985
#> 23 15.2 3.435  6.955
#> 24 13.3 3.840  7.275
#> 25 19.2 3.845  7.685
#> 26 27.3 1.935  5.780
#> 27 26.0 2.140  4.075
#> 28 30.4 1.513  3.653
#> 29 15.8 3.170  4.683
#> 30 19.7 2.770  5.940
#> 31 15.0 3.570  6.340
#> 32 21.4 2.780  6.350

Created on 2020-11-05 by the reprex package (v0.3.0.9001)

This topic was automatically closed 21 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.