[英]How to chain group_by, filter, distinct, count in data.table?
[英]dplyr into data.table: filter > group by > count
我通常使用dplyr
但面臨相當大的數據集,而且我的方法非常慢。 我基本上需要按日期過濾一個df
組,並計算其中的出現次數
樣本數據(已經將所有內容都轉換為data.table
)
library(data.table)
library(dplyr)
set.seed(123)
df <- data.table(startmonth = seq(as.Date("2014-07-01"),as.Date("2014-11-01"),by="months"),
endmonth = seq(as.Date("2014-08-01"),as.Date("2014-12-01"),by="months")-1)
df2 <- data.table(id = sample(1:10, 5, replace = T),
start = sample(seq(as.Date("2014-07-01"),as.Date("2014-10-01"),by="days"),5),
end = df$startmonth + sample(10:90,5, replace = T)
)
#cross joining
res <- setkey(df2[,c(k=1,.SD)],k)[df[,c(k=1,.SD)],allow.cartesian=TRUE][,k:=NULL]
我的dplyr
方法有效,但速度慢
res %>% filter(start <=endmonth & end>= startmonth) %>%
group_by(startmonth,endmonth) %>%
summarise(countmonth=n())
我的data.table
知識有限,但我想我們會在日期列上設置setkeys()
,例如res[ , :=( COUNT = .N , IDX = 1:.N ) , by = startmonth, endmonth]
來獲得按組計數,但我不確定過濾器如何進入該組。
感謝您的幫助!
您可以在聯接中進行計數:
df2[df, on=.(start <= endmonth, end >= startmonth), allow.cartesian=TRUE, .N, by=.EACHI]
start end N
1: 2014-07-31 2014-07-01 1
2: 2014-08-31 2014-08-01 4
3: 2014-09-30 2014-09-01 5
4: 2014-10-31 2014-10-01 3
5: 2014-11-30 2014-11-01 3
或將其添加為df
的新列:
df[, n :=
df2[.SD, on=.(start <= endmonth, end >= startmonth), allow.cartesian=TRUE, .N, by=.EACHI]$N
]
這個怎么運作。 語法為x[i, on=, allow.cartesian=, j, by=.EACHI]
。 如果使用i
來查找x
值,則每一行。 符號.EACHI
表示將對i
每一行進行聚合( j=.N
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.