How to delete multiple columns in r dataframe?

I am trying to delete some columns in a dataframe. I want to know why it worked for a single column, but not with multiple columns for example it works

album2[,5]<- NULL

this does not work

album2[,c(5:7)]<- NULL
Error in `[<-.data.frame`(`*tmp*`, , 5:7, value = NULL) : 
replacement has 0 items, need 600

This also does not work.

for (i in 5: (length(album2)-1)){
 album2[,i]<- NULL
}
Error in `[<-.data.frame`(`*tmp*`, , i, value = NULL) : 
new columns would leave holes after existing columns
+9
source share
4 answers

Base subset:

album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7
+21
source

Adding an answer, as this was the greatest success when searching for "discard multiple columns in r":

The general version of deleting a single column, for example df$column1 <- NULL, is to use list(NULL):

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

This also works for position index:

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

, , , . ( ) , :

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

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

album2 <- album2[,-c(5,7)] #deletes columns 5 and 7
+4
source

@ Ahmed Elmahy, the following approach should help you when you have a vector of column names that you want to remove from your data frame:

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
source

Source: https://habr.com/ru/post/1622959/


All Articles