【问题标题】:How to select rows with conditions based on other columns如何根据其他列选择具有条件的行
【发布时间】: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


    【解决方案1】:

    这个怎么样:

    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
    

    或者,因为您只对独特的nos 感兴趣:

    dt[Year == 2014, "a" %in% type & uniqueN(type) > 1, by = no][(V1), no]
    #[1] 111 333
    

    如果您不想将类型列中的NAs 视为其他值,则可以将其修改为:

    dt[Year == 2014, "a" %in% type & uniqueN(na.omit(type)) > 1, by = no][(V1), no]
    #[1] 111 333
    

    【讨论】:

    • .SDif 之后是什么?
    • .SD 是子集的data.table(每组)
    【解决方案2】:

    我们也可以使用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
    

    dplyr 可以应用相同的方法

    library(dplyr)
    dt %>%
       group_by(no) %>% 
       filter(any(type=="a") & any(type!="a") & Year==2014)
    

    【讨论】:

      猜你喜欢
      • 2020-12-24
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 2019-12-13
      相关资源
      最近更新 更多