Drop data frame columns by name

后端 未结 20 2596
花落未央
花落未央 2020-11-22 01:06

I have a number of columns that I would like to remove from a data frame. I know that we can delete them individually using something like:

df$x <- NULL
<         


        
20条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 01:37

    Dplyr Solution

    I doubt this will get much attention down here, but if you have a list of columns that you want to remove, and you want to do it in a dplyr chain I use one_of() in the select clause:

    Here is a simple, reproducable example:

    undesired <- c('mpg', 'cyl', 'hp')
    
    mtcars <- mtcars %>%
      select(-one_of(undesired))
    

    Documentation can be found by running ?one_of or here:

    http://genomicsclass.github.io/book/pages/dplyr_tutorial.html

提交回复
热议问题