Drop data frame columns by name

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

    Provide the data frame and a string of comma separated names to remove:

    remove_features <- function(df, features) {
      rem_vec <- unlist(strsplit(features, ', '))
      res <- df[,!(names(df) %in% rem_vec)]
      return(res)
    }
    

    Usage:

    remove_features(iris, "Sepal.Length, Petal.Width")
    

提交回复
热议问题