【问题标题】:Remove multiple rows with specific string values删除具有特定字符串值的多行
【发布时间】:2019-01-07 21:58:44
【问题描述】:

我有一个包含几百列的数据框。我想删除值为“跳过项目”或“”的选定列的行。

请参见下面的示例。理想情况下,我想删除列“动物”和“保险”包含“跳过项目”或“”的所有行,但不希望这适用于其他列。

在我的实际数据框中,大约有 34 列我想删除带有这些字符串的列,而 128 列我不想。建议将不胜感激。

dat <- data.frame(animal=c("dog","cat","Item skipped", ""), Insurance=c("Y", "N","Item skipped",""), condition = c("",
                  "Asthma","Item skipped",""), age = rep(c(6,10), each = 2))

【问题讨论】:

    标签: r dplyr purrr


    【解决方案1】:

    您可以将filter_at 用于选定的列或列范围

    library(dplyr)
    
    dat %>%
      filter_at(vars(animal,Insurance), all_vars(!. %in% c("Item skipped", "")))
    
    #  animal Insurance condition age
    #1    dog         Y             6
    #2    cat         N    Asthma   6
    

    或者使用 base R 你可以使用rowSums

    cols <- c('animal', 'Insurance')
    dat[rowSums(dat[cols] == "Item skipped" | dat[cols] == "") == 0, ]
    

    【讨论】:

    • 谢谢。如果我想使用 dplyr 但想按名称列出列,因为它们不是连续的,即 dat %>% filter_at(vars(animal,Insurance), any_vars(!. %in% c("Item skipped", "" )))
    • @monkeyshines 我最初犯了一个错误,您可能需要all_vars 而不是any_vars。我已经更新了答案。
    【解决方案2】:

    在没有for 循环的基础 R 中:

    dat[!rownames(dat) %in% which(dat$animal %in% c("Item skipped", "") | dat$Insurance %in% c("Item skipped", "")), ]`
    

    【讨论】:

      【解决方案3】:

      您始终可以使用 for 循环来执行此操作,尤其是因为您的数据集很小。

      > remove_cols <- c('animal', 'Insurance') # vector of names of all columns you'll use to drop rows
      > remove_vals <- c('', 'Item skipped') # values which indicate a row that should be dropped
      > 
      > for(col in remove_cols){
      +   dat <- dat[!dat[[col]] %in% remove_vals, ]
      + }
      > 
      > head(dat)
        animal Insurance condition age
      1    dog         Y             6
      2    cat         N    Asthma   6
      

      【讨论】:

        【解决方案4】:

        使用 R base 无需应用更多包:

        # Find rows that match content of 2 column cell values.
        rows_to_delete <- which(dat$animal == "Item skipped" & dat$Insurance == "Item skipped")
        
        # Delete row. 
        # Add result in new dataframe [dat2].
        # Keep old dataframe for comparison [dat].
        dat2 <- dat[-rows_to_delete, ]
        

        【讨论】:

          猜你喜欢
          • 2020-06-15
          • 1970-01-01
          • 1970-01-01
          • 2019-03-27
          • 1970-01-01
          • 2018-12-08
          • 1970-01-01
          • 2021-12-14
          相关资源
          最近更新 更多