Drop data frame columns by name

后端 未结 20 2597
花落未央
花落未央 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:48

    Here is a dplyr way to go about it:

    #df[ -c(1,3:6, 12) ]  # original
    df.cut <- df %>% select(-col.to.drop.1, -col.to.drop.2, ..., -col.to.drop.6)  # with dplyr::select()
    

    I like this because it's intuitive to read & understand without annotation and robust to columns changing position within the data frame. It also follows the vectorized idiom using - to remove elements.

提交回复
热议问题