R 如何基于其他列选择具有条件的行
根据数据表R 如何基于其他列选择具有条件的行,r,data.table,R,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')) 我想过滤掉任何不同时包含“a”和其他('b'、'c'等)的no。这意味着,ID222444和666将被过
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'))
我想过滤掉任何不同时包含“a”和其他('b'、'c'等)的no
。这意味着,ID222444和666将被过滤掉。请注意,由于2015年的原因,no
555被过滤掉
我期望的回报是
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])
setkey(dt,年份)
dt1这个怎么样:
dt[Year == 2014, if("a" %in% type & uniqueN(type) > 1) .SD, by = no]
# no Year type
#1: 111 2014 a
#2: 111 2014 b
#3: 111 2014 c
#4: 333 2014 a
#5: 333 2014 f
或者,由于您只对唯一的no
s感兴趣:
dt[Year == 2014, "a" %in% type & uniqueN(type) > 1, by = no][(V1), no]
#[1] 111 333
如果您的类型列中可能存在不想算作其他值的NA
s,您可以将其修改为:
dt[Year == 2014, "a" %in% type & uniqueN(na.omit(type)) > 1, by = no][(V1), no]
#[1] 111 333
这个怎么样:
dt[Year == 2014, if("a" %in% type & uniqueN(type) > 1) .SD, by = no]
# no Year type
#1: 111 2014 a
#2: 111 2014 b
#3: 111 2014 c
#4: 333 2014 a
#5: 333 2014 f
或者,由于您只对唯一的no
s感兴趣:
dt[Year == 2014, "a" %in% type & uniqueN(type) > 1, by = no][(V1), no]
#[1] 111 333
如果您的类型列中可能存在不想算作其他值的NA
s,您可以将其修改为:
dt[Year == 2014, "a" %in% type & uniqueN(na.omit(type)) > 1, by = no][(V1), no]
#[1] 111 333
我们也可以使用any
res <- dt[Year==2014, if(any(type=="a") & any(type!="a")) .SD, no]
res
# no Year type
#1: 111 2014 a
#2: 111 2014 b
#3: 111 2014 c
#4: 333 2014 a
#5: 333 2014 f
unique(res$no)
#[1] 111 333
我们也可以使用any
res <- dt[Year==2014, if(any(type=="a") & any(type!="a")) .SD, no]
res
# no Year type
#1: 111 2014 a
#2: 111 2014 b
#3: 111 2014 c
#4: 333 2014 a
#5: 333 2014 f
unique(res$no)
#[1] 111 333
.SD
在if
之后是什么?.SD
是子集数据表(每组)什么是.SD
在if
之后是什么?.SD
是子集数据表(每组)