Drop data frame columns by name

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

    Find the index of the columns you want to drop using which. Give these indexes a negative sign (*-1). Then subset on those values, which will remove them from the dataframe. This is an example.

    DF <- data.frame(one=c('a','b'), two=c('c', 'd'), three=c('e', 'f'), four=c('g', 'h'))
    DF
    #  one two three four
    #1   a   d     f    i
    #2   b   e     g    j
    
    DF[which(names(DF) %in% c('two','three')) *-1]
    #  one four
    #1   a    g
    #2   b    h
    

提交回复
热议问题