Drop data frame columns by name

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

    You can use a simple list of names :

    DF <- data.frame(
      x=1:10,
      y=10:1,
      z=rep(5,10),
      a=11:20
    )
    drops <- c("x","z")
    DF[ , !(names(DF) %in% drops)]
    

    Or, alternatively, you can make a list of those to keep and refer to them by name :

    keeps <- c("y", "a")
    DF[keeps]
    

    EDIT : For those still not acquainted with the drop argument of the indexing function, if you want to keep one column as a data frame, you do:

    keeps <- "y"
    DF[ , keeps, drop = FALSE]
    

    drop=TRUE (or not mentioning it) will drop unnecessary dimensions, and hence return a vector with the values of column y.

提交回复
热议问题