我想了解您对一种更优雅的方式来计算前几天发生的事件数量的想法。我的代码(如下)可以工作,但它不是很好,也不是可扩展的。我正在尝试访问底部的表(desired_table)。有什么想法吗?
我想以比这更优雅的方式计算前几天事件的总和。
require(data.table)
# simulating an example data.table
date <- c("2000-01-01", "2000-01-04", "2000-01-05", "2000-01-06", "2000-01-01", "2000-01-02", "2000-01-03", "2000-01-04", "2000-01-05", "2000-01-06" , "2000-01-01", "2000-01-04", "2000-01-05", "2000-01-06", "2000-01-01", "2000-01-02", "2000-01-03", "2000-01-04", "2000-01-05", "2000-01-06")
cohort <- c("a", "b", "c")
zz <- data.table(DATE = date, COHORT = cohort)
zz$DATE <- as.Date(zz$DATE) # making sure the date is in the correct format
# adding on some other date fields so we can summarise by these days as well
zz$d1 <- zz$DATE +1 # will become "yesterday" when joined
zz$d2 <- zz$DATE +2 # will become "day before yesterday", when joined
# summarising the data for the first date
summary1 <- zz[,list(events_today = .N ), by= c("DATE", "COHORT")]
# summarising the data for the previous
summary2 <- zz[,list(events_yesterday = .N ), by= c("d1", "COHORT")]
# summarising the data for the day before yesterday
summary3 <- zz[,list(events_day_before_yesterday = .N ), by= c("d2", "COHORT")]
# merging the tables together
summary1.2 <- merge(summary1, summary2, by.x = c("DATE", "COHORT"), by.y = c("d1", "COHORT"), all = TRUE)
# merging the tables together to join on third summary table.
desired_table <- merge(summary1.2, summary3, by.x = c("DATE", "COHORT"), by.y = c("d2", "COHORT"), all = TRUE)
print(desired_table)
必须有一种更优雅的方法来做到这一点吗?
我这里的例子很简单 - 实际上我可能想要对数千条记录和许多时间段执行此操作。
最佳答案
我认为更优雅的方式是
long_zz <- melt(zz, id.vars = "COHORT")
new_zz <- dcast(long_zz, COHORT + value ~ variable, fun = length, drop = FALSE, fill = NA)
new_zz
# COHORT value DATE d1 d2
# 1: a 2000-01-01 1 NA NA
# 2: a 2000-01-02 1 1 NA
# 3: a 2000-01-03 1 1 1
# 4: a 2000-01-04 NA 1 1
# 5: a 2000-01-05 2 NA 1
# 6: a 2000-01-06 2 2 NA
# 7: a 2000-01-07 NA 2 2
# 8: a 2000-01-08 NA NA 2
# 9: b 2000-01-01 2 NA NA
# 10: b 2000-01-02 NA 2 NA
# 11: b 2000-01-03 1 NA 2
# 12: b 2000-01-04 2 1 NA
# 13: b 2000-01-05 NA 2 1
# 14: b 2000-01-06 2 NA 2
# 15: b 2000-01-07 NA 2 NA
# 16: b 2000-01-08 NA NA 2
# 17: c 2000-01-01 1 NA NA
# 18: c 2000-01-02 1 1 NA
# 19: c 2000-01-03 NA 1 1
# 20: c 2000-01-04 2 NA 1
# 21: c 2000-01-05 2 2 NA
# 22: c 2000-01-06 NA 2 2
# 23: c 2000-01-07 NA NA 2
# 24: c 2000-01-08 NA NA NA
# COHORT value DATE d1 d2
这里,我首先将数据从宽格式转换为长格式,然后使用种姓将变量(DATE、d1、d2)再次拆分为列,同时计算每个 COHORT 中的行数,值组为每个变量。
如果没有 drop = FALSE
,我们将错过第 24 行,其中 COHORT c 没有发生任何事件。
您可以使用
设置您的姓名setnames(new_zz, c("value", "DATE", "d1", "d2"), c("DATE", "events_today","events_yesterday","events_day_before_yesterday"))
mircobenchmark
- 你的方法(合并)与我的方法(long_wide)的结果:
Unit: milliseconds
expr min lq mean median uq max neval
merge 14.740983 18.534281 31.88430 21.223305 31.830966 353.3662 100
long_wide 5.102077 6.411999 10.82941 7.130821 8.884161 117.7351 100
关于r - 您知道一种更优雅的方法来计算前几天的事件数量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56990258/