Вы можете использовать diff
:
transform(df, entry = c(cum_entry[1], diff(cum_entry)))
# Day cum_entry entry
#1 1 0 0
#2 2 1 1
#3 3 2 1
#4 3 2 0
#5 4 3 1
#6 4 3 0
В dplyr
, мы можем использовать lag
:
library(dplyr)
df %>% mutate(entry = cum_entry - lag(cum_entry, default = 0))
Или shift
в data.table
library(data.table)
setDT(df)[, entry := cum_entry - shift(cum_entry, fill = 0)]
данные
df <- data.frame(Day = c(1, 2, 3, 3, 4, 4), cum_entry = c(0, 1, 2, 2, 3, 3))