R:按日期切割并按ID与data.table分组 [英] R: cut by date and grouping by ID with data.table

查看:94
本文介绍了R:按日期切割并按ID与data.table分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data.table ,其中包含由 id 日期。对角色在特定的日期完成的工作数量没有限制。

I have a data.table with with a list of actors uniquely identified by id doing things on a date. There is no limit to number of things done by an actor on a particular 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))

现在,我想总结一下我的数据集,找出以下序列的每个间隔的出现次数

Now I want to summarise my dataset finding the number of occurrences for each of the intervals of the following sequence

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

一切都很好,但现在代替

All good. But now instead of counting the occurrences I would like to count the number of actors active in each interval, that is with one or more occurrences.

推荐答案

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())

In case you are using the development version 1.9.5 from GitHub you could use uniqueN() instead of length(unique()).

这篇关于R:按日期切割并按ID与data.table分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆