【问题标题】:Filter at any vars that match one of multiple conditions in R dplyr在与 R dplyr 中的多个条件之一匹配的任何变量处过滤
【发布时间】:2020-06-19 22:11:56
【问题描述】:

我正在参加泰坦尼克号 kaggle 比赛并且得到了简单的问题。如何过滤任何列中的 NA 和空值? 我知道如何逐个变量地做它,但想在过滤器语句中放置 2 个条件。到目前为止我得到了这个:

na_count = titanic.full %>%
  filter_at(vars(-Survived), any_vars(is.na(.)) || . == "")

所以我真正想要实现的是在 barplot 上可视化每列中有多少 NA 或“”(空),以便稍后我可以输入缺失的数据。

谢谢:)

【问题讨论】:

    标签: r filter dplyr


    【解决方案1】:

    要过滤 NA 并从选定的列中清空值,您可以使用 filter_at as :

    library(dplyr)
    titanic.full %>% filter_at(vars(-Survived), any_vars(is.na(.) | . == ""))
    

    要计算每列中NA 或空值的数量,我们可以使用summarise_all

    titanic.full %>% summarise_all(~sum(is.na(.) | . == ""))
    
    #  PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
    #1           0        0      0    0   0 177     0     0      0    0   687        2
    

    【讨论】:

    • 完美,正是我想要的!
    【解决方案2】:

    base R,我们可以使用rowSums

    nm1 <- setdiff(names(titanic.full), 'Survived')
    titanic.full[rowSums(is.na(titanic.full[nm1])| titanic.full[nm1] == "") > 0,\
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      相关资源
      最近更新 更多