Drop data frame columns by name

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

    within(df, rm(x))
    

    is probably easiest, or for multiple variables:

    within(df, rm(x, y))
    

    Or if you're dealing with data.tables (per How do you delete a column by name in data.table?):

    dt[, x := NULL]   # Deletes column x by reference instantly.
    
    dt[, !"x"]   # Selects all but x into a new data.table.
    

    or for multiple variables

    dt[, c("x","y") := NULL]
    
    dt[, !c("x", "y")]
    

提交回复
热议问题