how to remove multiple columns in r dataframe?

后端 未结 5 470
失恋的感觉
失恋的感觉 2020-12-25 13:12

I am trying to remove some columns in a dataframe. I want to know why it worked for a single column but not with multible columns e.g. this works

album2[,5]         


        
5条回答
  •  感动是毒
    2020-12-25 13:36

    Adding answer as this was the top hit when searching for "drop multiple columns in r":

    The general version of the single column removal, e.g df$column1 <- NULL, is to use list(NULL):

    df[ ,c('column1', 'column2')] <- list(NULL)

    This also works for position index as well:

    df[ ,c(1,2)] <- list(NULL)

    This is a more general drop and as some comments have mentioned, removing by indices isn't recommended. Plus the familiar negative subset (used in other answers) doesn't work for columns given as strings:

    > iris[ ,-c("Species")]
    Error in -"Species" : invalid argument to unary operator
    

提交回复
热议问题