【问题标题】:Removing 'FALSE' and 'NAs' from a dataframe从数据框中删除“FALSE”和“NAs”
【发布时间】:2021-11-24 10:56:45
【问题描述】:

我想从大型数据框中删除“FALSE”和“NAs”。我的输入看起来像,

ID Codes
1 TRUE
2 NA
3 FALSE
4 TRUE

我需要的输出是,

ID Codes
1 TRUE
4 TRUE

请建议在 R 中执行此操作的最佳方法 谢谢

【问题讨论】:

    标签: r dataframe filter dplyr subset


    【解决方案1】:

    我们可以只使用subset并指定Codes(假设它是逻辑列,NA将被删除)

    subset(df1, Codes)
      ID Codes
    1  1  TRUE
    4  4  TRUE
    

    数据

    df1 <- structure(list(ID = 1:4, Codes = c(TRUE, NA, FALSE, TRUE)), 
    class = "data.frame", row.names = c(NA, 
    -4L))
    

    【讨论】:

      【解决方案2】:

      如果您的Codes 是字符类型:

      library(dplyr)
      df %>%
        filter(Codes == "TRUE")
      

      如果它们是合乎逻辑的:

      df %>%
        filter(Codes)
      

      【讨论】:

      • 第二种情况甚至不需要== TRUE 部分。
      • 感谢您指出这一点!
      • 但是,老实说,使用== TRUE 更容易阅读/理解。
      【解决方案3】:

      这是另一种基本的 R 方法:使用 complete.cases

      df1$Codes[df1$Codes == FALSE] <- NA
      df1[complete.cases(df1),]
      

      输出:

        ID Codes
      1  1  TRUE
      4  4  TRUE
      

      【讨论】:

      • df1[df1$Codes &amp; !is.na(df1$Codes),]
      猜你喜欢
      • 2016-09-09
      • 2021-05-19
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多