【发布时间】:2016-01-14 09:51:00
【问题描述】:
给定data.table,
library(data.table)
dt <- data.table(Year=c(rep(2014,1,8), 2015, 2014, 2014), no=c(111,111,111,222,222,333,333,444,555,666,666), type=c('a','b','c','a','a','a','f','a', 'a', 'c','f'))
返回,
Year no type
1: 2014 111 a
2: 2014 111 b
3: 2014 111 c
4: 2014 222 a
5: 2014 222 a
6: 2014 333 a
7: 2014 333 f
8: 2014 444 a
9: 2015 555 a
10: 2014 666 c
11: 2014 666 f
我想过滤掉任何不包含“a”和其他(“b”、“c”等)的no。这意味着 id 222、444 和 666 将被过滤掉。请注意,no 555 因 2015 年而被过滤掉。
我期望的回报是
Year no type
1: 2014 111 a
2: 2014 111 b
3: 2014 111 c
4: 2014 333 a
5: 2014 333 f
然后,我们使用unique 最终得到no 111 和333 作为我们的最终结果。
我尝试了以下方法:
setkey(dt, Year)
dt1 <- dt[J(2014)][,.(type=unique(type)), by = no]
unique(na.omit(merge(dt1[type=='a'],dt1[type!='a'], by = 'no', all = T))[,no])
但是,我认为这段代码效率不高。 你能给我建议吗?
【问题讨论】:
标签: r data.table