我有一个数据表,其中包含数千个可以通过唯一ID识别的公司。它是长格式数据,每个公司应该在不同年份出现两次(横截面时间序列超过两年)。
然而,并非所有公司都出现在这两年中,我正在努力创建一个平衡的长格式小组,其中只有公司仍然出现在这两年。我该如何做到这一点?
这是一个示例数据表来说明问题:
example <- matrix(c(1,1,2,3,3,2013,2016,2013,2013,2016), ncol=2)
colnames(example) <- c('id', 'year')
example.table <- data.table(example)
example.table
id year
1: 1 2013
2: 1 2016
3: 2 2013
4: 3 2013
5: 3 2016
在示例中,我需要一个代码/函数,允许我排除ID为“2”的公司行,因为它在2016年没有匹配。换句话说:我需要一个代码/函数来比较每一行与如果id列中没有匹配项,则前一行和后一行将其排除。
我投入了很多时间,但似乎已达到我的R知识的极限,并将感谢任何支持。谢谢!
使用dplyr
如下:
library(dplyr)
example.table %>%
group_by(id) %>%
filter(n() > 1)
# A tibble: 4 x 2
# Groups: id [2]
id year
<dbl> <dbl>
1 1 2013
2 1 2016
3 3 2013
4 3 2016
我们从整个数据集创建一个unique
'年'的向量,然后检查all
'nm1'中的值是%in%
'year'按'id'分组并且是data.table的子集
un1 <- unique(example.table$year)
example.table[, .SD[all(un1 %in% year)], id]
# id year
#1: 1 2013
#2: 1 2016
#3: 3 2013
#4: 3 2016
注意:OP的数据集是data.table
,使用的方法是data.table
。最初,考虑使用.SD[uniqueN(year) > 1]
,但这是错误的,可能不适用于所有情况
data.table
对@ Sonny的dplyr
解决方案的等效解决方案
example.table[, if(.N > 1) .SD, id]
id year
1: 1 2013
2: 1 2016
3: 3 2013
4: 3 2016