how to remove multiple columns in r dataframe?

后端 未结 5 420
失恋的感觉
失恋的感觉 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:33

    @Ahmed Elmahy following approach should help you out, when you have got a vector of column names you want to remove from your dataframe:

    test_df <- data.frame(col1 = c("a", "b", "c", "d", "e"), col2 = seq(1, 5), col3 = rep(3, 5))
    rm_col <- c("col2")
    test_df[, !(colnames(test_df) %in% rm_col), drop = FALSE]
    

    All the best, ExploreR

    0 讨论(0)
  • 2020-12-25 13:33

    x <-dplyr::select(dataset_df, -c('coloumn1', 'column2'))

    This works for me.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-25 13:46

    Basic subsetting:

    album2 <- album2[, -5] #delete column 5
    album2 <- album2[, -c(5:7)] # delete columns 5 through 7
    
    0 讨论(0)
  • 2020-12-25 13:56

    If you only want to remove columns 5 and 7 but not 6 try:

    album2 <- album2[,-c(5,7)] #deletes columns 5 and 7
    
    0 讨论(0)
提交回复
热议问题