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

问题描述 投票:0回答:1

下面是我的数据;

enter image description here

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

enter image description here

请提出解决方案的建议。

谢谢

r sum formula
1个回答
0
投票

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

0
投票

答案是diff

cumulative <- c(0,1,2,2,3,3)
diff(cumulative)
# [1] 1 1 0 1 0
© www.soinside.com 2019 - 2024. All rights reserved.