R:按日期切割并按 ID 分组 data.table
R: cut by date and grouping by ID with data.table
我有一个 data.table
,其中包含由 id
在 date
上做事唯一标识的演员列表。 actor
在特定 date
上完成的事情数量没有限制。
require(data.table)
set.seed(28100)
df.in <- data.table(id = sample(1:10, 100, replace=TRUE),
date = sample(2001:2012, 100, replace=TRUE))
现在我想总结我的数据集,找出以下序列每个间隔的出现次数
sequence <- seq(2000, 2012, 4)
df.out1 <- as.data.frame(table(cut(df.in$date, breaks = sequence)))
df.out1
# Var1 Freq
# 1 (2000,2004] 35
# 2 (2004,2008] 27
# 3 (2008,2012] 38
一切顺利。但是现在我不想计算发生次数,而是想计算每个时间间隔内活跃的演员数量,即发生一次或多次。
你的意思是这样的吗?
df.in[, interv := cut(date, sequence)][, .(Actors = length(unique(id))), by = interv]
# interv Actors
#1: (2000,2004] 10
#2: (2008,2012] 9
#3: (2004,2008] 10
如果您使用的是 GitHub 的开发版本 1.9.5,您可以使用 uniqueN()
而不是 length(unique())
。
我有一个 data.table
,其中包含由 id
在 date
上做事唯一标识的演员列表。 actor
在特定 date
上完成的事情数量没有限制。
require(data.table)
set.seed(28100)
df.in <- data.table(id = sample(1:10, 100, replace=TRUE),
date = sample(2001:2012, 100, replace=TRUE))
现在我想总结我的数据集,找出以下序列每个间隔的出现次数
sequence <- seq(2000, 2012, 4)
df.out1 <- as.data.frame(table(cut(df.in$date, breaks = sequence)))
df.out1
# Var1 Freq
# 1 (2000,2004] 35
# 2 (2004,2008] 27
# 3 (2008,2012] 38
一切顺利。但是现在我不想计算发生次数,而是想计算每个时间间隔内活跃的演员数量,即发生一次或多次。
你的意思是这样的吗?
df.in[, interv := cut(date, sequence)][, .(Actors = length(unique(id))), by = interv]
# interv Actors
#1: (2000,2004] 10
#2: (2008,2012] 9
#3: (2004,2008] 10
如果您使用的是 GitHub 的开发版本 1.9.5,您可以使用 uniqueN()
而不是 length(unique())
。