【发布时间】:2026-02-16 03:50:02
【问题描述】:
我有一个包含 id、id_create_date 和 id_closed_date 的表。假设 id_create_date 从 2021-01-01 开始到今天。在某些日子里,没有 id 创建或 id 关闭。
| ID | id_create_date | id_closed_date |
|---|---|---|
| 1 | 2021-03-01 | 2021-03-01 |
| 2 | 2021-03-02 | NA |
| 3 | 2021-03-04 | 2021-04-11 |
| 4 | 2021-03-05 | 2021-03-22 |
我想要一个汇总表来统计从年初到今天每天创建了多少 id,关闭了多少 id,还有多少 id 仍然开放。
| Date | number of opened | number of closed | number of still open |
|---|---|---|---|
| 2021-03-01 | 1 | 1 | 0 |
| 2021-03-02 | 1 | 0 | 1 |
| 2021-03-03 | 0 | 0 | 1 |
| 2021-03-04 | 1 | 0 | 2 |
| 2021-03-05 | 1 | 0 | 3 |
| 2021-03-06 | . | . | . |
| . | . | . | . |
| . | . | . | . |
| 2021-04-11 | 1 | 0 | 1 |
为了获得所需的表,我创建了日历表并尝试将其与主表连接。有一个在 sql 中使用交叉连接的解决方法。但我正在寻找一种方法来使用 data.table 或 dplyr 或其他不同的方法。
数据量很大,所以我使用 data.table 来操作数据。但是,我无法创建如何根据日历日期计算 id 的方式并使用不公平的连接。
我尝试了很多方法,但找不到解决方案。
test3 <- test1[test2, on = .(calender_date>= id_created_at),allow.cartesian=TRUE, nomatch = 0]
我发现的唯一方法是循环。但是表太大,所以循环不会结束。以下代码为循环版本。
newtable=data.frame(matrix(ncol = 4, nrow = 0),stringsAsFactors = FALSE)
start.time <- Sys.time()
i=1
while(i<=length(calendar[calendar<=Sys.Date()])){
numberofids=length(unique(
inbouds$id_id[which(inbouds$id_created_at==calendar[i])] ))
numberofclosedids=length(unique(
inbouds$id_id[which(inbouds$id_closed_at==calendar[i])] ))
numberofPendingids=length(unique(
inbouds$id_id[which(inbouds$id_created_at<calendar[i] &
(is.na(inbouds$id_closed_at) | inbouds$id_closed_at>=calendar[i]))] ))
subdata=cbind(as.character(calendar[i]),as.numeric(numberofids),as.numeric(numberofclosedids),as.numeric(numberofPendingids))
subdata= as.data.frame(subdata,stringsAsFactors = FALSE)
newtable=rbind(newtable,subdata)
i=i+1
}
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken
newtable=setNames(newtable, c("date", "#ofidOpened", "#ofidClosed", "#ofidPending"))
newtable$date= as.character(newtable$date)
newtable$`#ofidOpened`= as.numeric(newtable$`#ofidOpened`)
newtable$`#ofidClosed`= as.numeric(newtable$`#ofidClosed`)
newtable$`#ofidPending`= as.numeric(newtable$`#ofidPending`)
【问题讨论】:
-
可以添加
dput(your_data)的输出
标签: r join data.table cross-join inequality