r - Drop data frame columns by name

ID : 1529

viewed : 131

Tags : rdataframer-faqr





Top 5 Answer for r - Drop data frame columns by name

vote vote

93

You can use a simple list of names :

DF <- data.frame(   x=1:10,   y=10:1,   z=rep(5,10),   a=11:20 ) drops <- c("x","z") DF[ , !(names(DF) %in% drops)] 

Or, alternatively, you can make a list of those to keep and refer to them by name :

keeps <- c("y", "a") DF[keeps] 

EDIT : For those still not acquainted with the drop argument of the indexing function, if you want to keep one column as a data frame, you do:

keeps <- "y" DF[ , keeps, drop = FALSE] 

drop=TRUE (or not mentioning it) will drop unnecessary dimensions, and hence return a vector with the values of column y.

vote vote

90

There's also the subset command, useful if you know which columns you want:

df <- data.frame(a = 1:10, b = 2:11, c = 3:12) df <- subset(df, select = c(a, c)) 

UPDATED after comment by @hadley: To drop columns a,c you could do:

df <- subset(df, select = -c(a, c)) 
vote vote

80

within(df, rm(x)) 

is probably easiest, or for multiple variables:

within(df, rm(x, y)) 

Or if you're dealing with data.tables (per How do you delete a column by name in data.table?):

dt[, x := NULL]   # Deletes column x by reference instantly.  dt[, !"x"]   # Selects all but x into a new data.table. 

or for multiple variables

dt[, c("x","y") := NULL]  dt[, !c("x", "y")] 
vote vote

68

You could use %in% like this:

df[, !(colnames(df) %in% c("x","bar","foo"))] 
vote vote

56

list(NULL) also works:

dat <- mtcars colnames(dat) # [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" # [11] "carb" dat[,c("mpg","cyl","wt")] <- list(NULL) colnames(dat) # [1] "disp" "hp"   "drat" "qsec" "vs"   "am"   "gear" "carb" 

Top 3 video Explaining r - Drop data frame columns by name







Related QUESTION?