Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove multiple columns in r dataframe?

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 
like image 329
Ahmed Elmahy Avatar asked Jan 05 '16 17:01

Ahmed Elmahy


People also ask

How do I remove multiple columns in a Dataframe in R?

We can delete multiple columns in the R dataframe by assigning null values through the list() function.

How do I remove columns from a data in R?

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.

How do you delete multiple columns?

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.

How do I remove columns from column names in R?

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.


1 Answers

Basic subsetting:

album2 <- album2[, -5] #delete column 5 album2 <- album2[, -c(5:7)] # delete columns 5 through 7 
like image 107
doctorG Avatar answered Sep 19 '22 16:09

doctorG