1

From this data I want a new column ("from") with the first value for each row of cumulative values. It should actually be the last value from column "cum" + 1. How would you do this with a function? Imagine many rows.

     a <- c(5,5,4,3)
cum <- cumsum(a)
df <- data.frame(a,cum)
df
  a cum 
  5   5  
  5  10  
  4  14 
  3  17  

df$from <- c(1,6,11,15)
 df
  a cum from
  5   5    1
  5  10    6
  4  14   11
  3  17   15
user11916948
  • 944
  • 5
  • 12
  • See [Basic lag in R vector/dataframe](https://stackoverflow.com/questions/3558988/basic-lag-in-r-vector-dataframe) for many examples. E.g. build on [this](https://stackoverflow.com/a/27239729/1851712): `c(1, head(df$cum, -1) + 1)`. – Henrik Mar 01 '21 at 12:02

3 Answers3

1

One possible solution is using lag() and then head() to remove the last element of the created vector

df$from <- head(c(1, lag(df$cum + 1)), -1)

df
#   a cum from
# 1 5   5    1
# 2 5  10    6
# 3 4  14   11
# 4 3  17   15
Ric S
  • 9,073
  • 3
  • 25
  • 51
1
library(tidyverse) 
a <- c(5,5,4,3)
cum <- cumsum(a)
df <- data.frame(a,cum)

df %>% 
  mutate(from = lag(cum, default = 0) + 1)
#>   a cum from
#> 1 5   5    1
#> 2 5  10    6
#> 3 4  14   11
#> 4 3  17   15

Created on 2021-03-01 by the reprex package (v1.0.0)

Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14
1

A base R option

transform(
  df,
  from = c(1, head(cum, -1) + 1)
)

gives

  a cum from
1 5   5    1
2 5  10    6
3 4  14   11
4 3  17   15
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81