如何从 R 中的每日数据中的累积数字中获取实际值

How to get the actual values from cumulative numbers from day wise data in R

下面是我的数据;

我想得到如下的实际条目;

请提出解决方案。

谢谢

你可以使用 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))

shiftdata.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))

答案是diff

cumulative <- c(0,1,2,2,3,3)
diff(cumulative)
# [1] 1 1 0 1 0