【问题标题】:Remove rows with a factor if zero value appears on another column如果零值出现在另一列上,则删除带有因子的行
【发布时间】:2019-08-02 13:19:29
【问题描述】:

我的数据框如下所示:

structure(list(intype = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L), .Label = c("A30", "A31", "E45"), class = "factor"), 
    inerror = c(0.54, 0.14, 0.94, 0, 2.11, 0, 1.42, 3.19, 0), 
    inmethod = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L
    ), .Label = c("A", "B", "C"), class = "factor")), row.names = c(NA, 
-9L), class = "data.frame")

+--------+---------+----------+
| intype | inerror | inmethod |
+--------+---------+----------+
| A30    |    0.54 | A        |
| A30    |    0.14 | B        |
| A30    |    0.94 | C        |
| A31    |    9.20 | A        |
| A31    |    2.11 | B        |
| A31    |   -1.55 | C        |
| E45    |    1.42 | A        |
| E45    |    3.19 | B        |
| E45    |    0.00 | C        |
+--------+---------+----------+

Intype 是一个因素。 如果inerror<=0,我想从一个因子中删除所有行。

所以生成的数据框将是:

+--------+---------+----------+
| intype | inerror | inmethod |
+--------+---------+----------+
| A30    |    0.54 | A        |
| A30    |    0.14 | B        |
| A30    |    0.94 | C        |
+--------+---------+----------+

【问题讨论】:

    标签: r dataframe filter


    【解决方案1】:

    有多种方法可以做到这一点

    library(dplyr)
    df %>%
      group_by(intype) %>%
      filter(all(inerror > 0))
    
    # intype inerror inmethod
    #  <fct>    <dbl> <fct>   
    #1 A30       0.54 A       
    #2 A30       0.14 B       
    #3 A30       0.94 C    
    

    或者它是倒置版本

    df %>%
      group_by(intype) %>%
      filter(!any(inerror <= 0))
    

    带基 R ave

    subset(df, ave(inerror > 0, intype, FUN = all))   
    #and
    subset(df, !ave(inerror <= 0, intype, FUN = any))      
    

    【讨论】:

      【解决方案2】:

      这也有效。

      with(dat, dat[- which(intype %in% intype[inerror <= 0]), ])
      

      或者,更短(谢谢@Ronak Shah

      with(dat, dat[!intype %in% intype[inerror <= 0], ]) 
      

      #   intype inerror inmethod
      # 1    A30    0.54        A
      # 2    A30    0.14        B
      # 3    A30    0.94        C
      

      要摆脱过时的因子水平,请在新数据框上使用 droplevels

      dat$intype <- droplevels(dat$intype)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-21
        • 2015-07-24
        • 1970-01-01
        • 1970-01-01
        • 2019-12-01
        • 2022-10-09
        相关资源
        最近更新 更多