是否有一个R函数可以撤消cumsum()并在数据集中重新创建原始的非累积列?
为了简单起见,我创建了一个小的虚拟数据集 请注意:日期为yyyy-mm-dd格式 以下是数据集DF:是否有一个R函数可以撤消cumsum()并在数据集中重新创建原始的非累积列?,r,date,lag,cumsum,cumulative-sum,R,Date,Lag,Cumsum,Cumulative Sum,为了简单起见,我创建了一个小的虚拟数据集 请注意:日期为yyyy-mm-dd格式 以下是数据集DF: DF%突变(累计访问量=累计访问量) #一个tibble:12x3 #组别:国家[3] 国家日期累计访问次数 1法国2020-01-01 10 2法国2020-01-02 26 3法国2020-01-03 40 4法国2020-01-04 52 5英格兰2020-01-01 11 6英格兰2020-01-02 20 7英格兰2020-01-03 32 8英格兰2020-01-04 46 9西班牙
DF%突变(累计访问量=累计访问量)
#一个tibble:12x3
#组别:国家[3]
国家日期累计访问次数
1法国2020-01-01 10
2法国2020-01-02 26
3法国2020-01-03 40
4法国2020-01-04 52
5英格兰2020-01-01 11
6英格兰2020-01-02 20
7英格兰2020-01-03 32
8英格兰2020-01-04 46
9西班牙2020-01-01 13
10西班牙2020-01-02 26
11西班牙2020-01-03 41
12西班牙2020-01-04 51
假设我只有数据集DFc。我可以使用哪些R函数来重新创建访问列(如数据集DF中所示)以及实质上的“撤消/反转”cumsum()?
有人告诉我,我可以合并lag()函数,但我不知道怎么做
此外,如果日期间隔几周而不是一天,代码将如何更改
任何帮助都将不胜感激:)从您的玩具示例开始:
library(dplyr)
DF <- tibble(country = rep(c("France", "England", "Spain"), each = 4),
date = rep(c("2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01"), times = 3),
visits = c(10, 16, 14, 12, 11, 9, 12, 14, 13, 13, 15, 10))
DF <- DF %>%
group_by(country) %>%
mutate(cumulative_visits = cumsum(visits)) %>%
ungroup()
从您的玩具示例开始:
library(dplyr)
DF <- tibble(country = rep(c("France", "England", "Spain"), each = 4),
date = rep(c("2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01"), times = 3),
visits = c(10, 16, 14, 12, 11, 9, 12, 14, 13, 13, 15, 10))
DF <- DF %>%
group_by(country) %>%
mutate(cumulative_visits = cumsum(visits)) %>%
ungroup()
这里有一个通用的解决方案。这是草率的,因为正如您所看到的,它没有返回
foo[1]
,但这是可以修复的。(倒转最后一行的输出也是如此。)我将把它留作“读者练习”
foo这里有一个通用的解决方案。这是草率的,因为正如您所看到的,它没有返回foo[1]
,但这是可以修复的。(倒转最后一行的输出也是如此。)我将把它留作“读者练习”
foo
DF1 <- DF %>%
# set to date!
mutate(date = as.Date(date)) %>%
# remove one date just for the sake of the example
filter(date != as.Date("2020-02-01"))
DF1 %>%
group_by(country) %>%
# complete and fill with zero!
tidyr::complete(date = seq.Date(min(date), max(date), by = "month"), fill = list(visits = 0)) %>%
# fill cumulative with the last available value
tidyr::fill(cumulative_visits) %>%
# reset in the same way
mutate(decum_visits1 = c(cumulative_visits[1], diff(cumulative_visits)),
decum_visits2 = cumulative_visits - lag(cumulative_visits, default = 0)) %>%
ungroup()
foo <- sample(1:20,10)
[1] 16 11 13 5 6 12 19 10 3 4
bar <- cumsum(foo)
[1] 16 27 40 45 51 63 82 92 95 99
rev(bar[-1])-rev(bar[-length(bar)])
[1] 4 3 10 19 12 6 5 13 11