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]
@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
x <-dplyr::select(dataset_df, -c('coloumn1', 'column2'))
This works for me.
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
Basic subsetting:
album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7
If you only want to remove columns 5 and 7 but not 6 try:
album2 <- album2[,-c(5,7)] #deletes columns 5 and 7