温馨提示:本文翻译自stackoverflow.com,查看原文请点击:r - Accumulating by date
aggregate dplyr for-loop loops r

r - 依日期累计

发布于 2020-03-27 10:18:42

我想知道在特定的一天会出现多少只动物。这张图描述了人们预先登记他们的动物。

例如,7在前几天,有人注册了他们的4猫来出现5/3/20196未来的几天,9还会有另一只猫被注册5/3/2019因此,会有7+6=13猫出现在上面5/3/2019

days_ahead= 0时,仅表示某人在活动当天进行了注册。例如,45/1/20195/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)。任何建议表示赞赏!

查看更多

查看更多

提问者
Rachel Zhang
被浏览
366
Cole 2019-07-03 21:13

使用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