R:汇总过去30天的数据

凯夫斯

作为一个新手,我希望了解如何使用任意回溯(例如从日期算起的前30天)汇总数据。请参阅下面的数据作为示例。我想按每个名称分组,然后汇总截至30年2月15日的30天的销售额。因此它将回顾从02-15-2019的30个日历日,并按名称提供我的总销售额(例如,人员1 = $ 60;人员2 = $ 30)

 Name      Date          Sales
Person1    01-31-2019    $10
Person1    02-15-2019    $50
Person1    06-18-2019    $100
Person2    01-31-2019    $25
Person2    02-15-2019    $5
Person2    06-18-2019    $200
斯拉瓦·科胡特

简单示例(如果我正确理解了您的问题):

library(dplyr) 
set.seed(123)
df <- data.frame(Name = sample(c("Person1", "Person2"), 6, T),
           Date = c("01-31-2019", "02-15-2019", "06-18-2019", "01-31-2019", "02-15-2019", "06-18-2019"),
           Sales = runif(6, 10, 100), stringsAsFactors = F)

df$Date <- lubridate::mdy(df$Date)

target <- lubridate::mdy("02-15-2019")
sales <- df %>% filter(between(Date, target - 30, target)) %>% 
  group_by(Name) %>% summarise(Sales = sum(Sales))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章