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]<- NULL
this doesn't work
album2[,c(5:7)]<- NULL Error in `[<-.data.frame`(`*tmp*`, , 5:7, value = NULL) : replacement has 0 items, need 600
This also doesn't 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
We can delete multiple columns in the R dataframe by assigning null values through the list() function.
The most easiest way to drop columns is by using subset() function. In the code below, we are telling R to drop variables x and z. The '-' sign indicates dropping variables. Make sure the variable names would NOT be specified in quotes when using subset() function.
If you need to remove multiple columns that are next to each other at once, select the first column of the batch – click on the left button of the mouse, then hold and drag through all the columns you want to delete.
In R, the easiest way to remove columns from a data frame based on their name is by using the %in% operator. This operator lets you specify the redundant column names and, in combination with the names() function, removes them from the data frame. Alternatively, you can use the subset() function or the dplyr package.
Basic subsetting:
album2 <- album2[, -5] #delete column 5 album2 <- album2[, -c(5:7)] # delete columns 5 through 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With