我想知道在特定的一天会出现多少只动物。这张图描述了人们预先登记他们的动物。
例如,7
在前几天,有人注册了他们的4
猫来出现5/3/2019
;在6
未来的几天,9
还会有另一只猫被注册5/3/2019
。因此,会有7+6=13
猫出现在上面5/3/2019
。
当days_ahead
= 0时,仅表示某人在活动当天进行了注册。例如,4
狼5/1/2019
在5/1/2019
(0天前)登记,并且4
那天会有狼。
library(dplyr)
set.seed(0)
animal = c(rep('cat', 5), rep('dog', 6), rep('wolf', 3))
date = sample(seq(as.Date("2019/5/1"), as.Date('2019/5/10'), by='day'), 14, replace=TRUE)
days_ahead = sample(seq(0,14), 14, replace=FALSE)
number = sample.int(10, 14, replace=TRUE)
dt = data.frame(animal, date, days_ahead, number) %>% arrange(animal, date)
预期结果应1-3
与示例具有相同的列,但第四列应是每个累加的数字date
,并在上累加days_ahead
。
我在这里添加了预期的结果。将comments
被用来解释accumulated_number
列。
我已经考虑过loop
函数,但不能完全确定如何遍历三个变量(cat,date和days_ahead)。任何建议表示赞赏!
使用accumulated_number
比较容易cumsum()
。请参阅您所在comments
领域的此链接:
dt%>%
group_by(animal,date)%>%
mutate(accumulated_number = cumsum(number)
,comments = Reduce(function(x1, x2) paste(x1, x2, sep = '+'), as.character(number), accumulate = T)
)%>%
ungroup()
而且,我的数据集与具有相同种子的数据集略有不同。尽管如此,它似乎仍然有效。
# A tibble: 14 x 6
animal date days_ahead number accumulated_number comments
<fct> <date> <int> <int> <int> <chr>
1 cat 2019-05-03 10 9 9 9
2 cat 2019-05-04 6 4 4 4
3 cat 2019-05-06 8 5 5 5
4 cat 2019-05-09 5 4 4 4
5 cat 2019-05-10 13 6 6 6
6 dog 2019-05-01 0 2 2 2
7 dog 2019-05-03 3 5 5 5
8 dog 2019-05-07 1 7 7 7
9 dog 2019-05-07 9 8 15 7+8
10 dog 2019-05-09 12 2 2 2
11 dog 2019-05-10 7 9 9 9
12 wolf 2019-05-02 14 5 5 5
13 wolf 2019-05-03 11 8 8 8
14 wolf 2019-05-07 4 9 9 9
我认为OP不需要
comments
专栏,仅用于解释。它只是cumsum
按组。@Ronak我认为你是对的。该
comments
是一种乐趣,以研究,虽然。我保留它。