【问题标题】:R dplyr drop column that may or may not exist select(-name)R dplyr 删除可能存在或不存在的列 select(-name)
【发布时间】:2020-03-15 00:50:59
【问题描述】:
library(ggplot2)
library(dplyr)

diamonds <- diamonds %>% select(-clarity)

# this works fine
# but doing it again gives me an error
diamonds %>% select(-clarity)

is_character(x) 中的错误:找不到对象“清晰度”

如何安全删除/取消选择?

【问题讨论】:

    标签: r select dplyr


    【解决方案1】:

    你可以这样做:

    diamonds %>% 
     select(-one_of("clarity"))
    

    如果有一个不存在的变量:

    diamonds %>% 
     select(-one_of("clarity", "clearness"))
    

    它返回一个警告:

    Warning message:
    Unknown columns: `clearness` 
    

    来自dplyr 1.0.0,可以使用any_of()

    diamonds %>% 
     select(-any_of(c("clarity", "clearness")))
    

    【讨论】:

    • 使用diamonds %&gt;% select(-one_of("clarity", "clearness")) %&gt;% suppressWarnings() 来避免警告。
    • 使用 tidyverse 1.3.0/dplyr 1.0.4 我收到一个错误(不是警告),列不存在。 select(-one_of("bad_col")) 的行为改变了吗?
    【解决方案2】:

    这里有一个使用dplyr::select_if() 的小改动,如果列名不存在,则不会引发Unknown columns: 警告,在本例中为“bad_column”:

    diamonds %>% 
      select_if(!names(.) %in% c('carat', 'cut', 'bad_column'))
    

    【讨论】:

      【解决方案3】:

      这是对 tmfmnk 显示的 one_of 方法的简单修改,以使用像 select 这样的符号。输入被转换为quosures,然后转换为字符。

      library(tidyverse) # or just dplyr and purrr
      
      drop_cols <- function(df, ...){
        df %>% 
          select(-one_of(map_chr(enquos(...), quo_name)))
      }
      
      diamonds %>% 
        drop_cols(clarity, color, zebra)
      
      # # A tibble: 53,940 x 8
      #    carat cut       depth table price     x     y     z
      #    <dbl> <ord>     <dbl> <dbl> <int> <dbl> <dbl> <dbl>
      #  1 0.23  Ideal      61.5    55   326  3.95  3.98  2.43
      #  2 0.21  Premium    59.8    61   326  3.89  3.84  2.31
      #  3 0.23  Good       56.9    65   327  4.05  4.07  2.31
      #  4 0.290 Premium    62.4    58   334  4.2   4.23  2.63
      #  5 0.31  Good       63.3    58   335  4.34  4.35  2.75
      #  6 0.24  Very Good  62.8    57   336  3.94  3.96  2.48
      #  7 0.24  Very Good  62.3    57   336  3.95  3.98  2.47
      #  8 0.26  Very Good  61.9    55   337  4.07  4.11  2.53
      #  9 0.22  Fair       65.1    61   337  3.87  3.78  2.49
      # 10 0.23  Very Good  59.4    61   338  4     4.05  2.39
      # # ... with 53,930 more rows
      # Warning message:
      # Unknown columns: `zebra`
      

      【讨论】:

        猜你喜欢
        • 2020-07-28
        • 1970-01-01
        • 2021-05-22
        • 2014-08-21
        • 2020-03-18
        • 1970-01-01
        • 2016-06-20
        • 2017-10-02
        • 1970-01-01
        相关资源
        最近更新 更多