【问题标题】:Subset data frame based on multiple conditions?基于多个条件的子集数据框?
【发布时间】:2018-12-06 12:32:45
【问题描述】:

我有一个数据框:df=data.frame(sample.id=c(1, 1, 2, 3, 4, 4, 5, 6, 7, 7), sample.type=c(U, S, S, U, U, D, D, U, U, D), cond = c(1.4, 17, 12, 0.45, 1, 7, 1, 9, 0, 14))

我想要一个数据框,它只包含同时具有 sample.type "U" 和 sample.type "D" 的 sample.id 行

新df:df.new=data.frame(sample.id=c(4, 4, 7, 7), sample.type=c(U, D, U, D), cond = c(1, 7, 0, 14))

最简单的方法是什么?重复不起作用,因为它将返回带有 U 和 S 以及 U 和 D 的 sample.ids。我不知道如何过滤/子集同时是 sample.type U 和 sample.type D 的样本 ID。感谢您的任何建议!

【问题讨论】:

    标签: r dataframe dplyr


    【解决方案1】:

    带data.table

    library(data.table)
    setDT(df)
    
    df[, if(all(c('U', 'D') %in% sample.type)) .SD, by = sample.id]
    

    【讨论】:

      【解决方案2】:

      filterany 一起使用

      df %>% group_by(sample.id) %>% filter(any(sample.type == 'U') & any(sample.type == 'D'))
      # A tibble: 4 x 3
      # Groups:   sample.id [2]
        sample.id sample.type  cond
            <dbl>      <fctr> <dbl>
      1         4           U     1
      2         4           D     7
      3         7           U     0
      4         7           D    14
      

      【讨论】:

        【解决方案3】:

        我们可以通过group 做一个filter

        library(dplyr)
        df %>% 
           group_by(sample.id) %>% 
           filter(all(c("U", "D") %in% sample.type))
        # A tibble: 4 x 3
        # Groups:   sample.id [2]
        #  sample.id sample.type  cond
        #      <dbl> <fct>       <dbl>
        #1         4 U               1
        #2         4 D               7
        #3         7 U               0
        #4         7 D              14
        

        【讨论】:

          猜你喜欢
          • 2016-03-19
          • 2011-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-01
          • 2020-09-26
          • 1970-01-01
          相关资源
          最近更新 更多