Skip to content
Fix Code Error

Drop data frame columns by name

March 13, 2021 by Code Error
Posted By: Anonymous

I have a number of columns that I would like to remove from a data frame. I know that we can delete them individually using something like:

df$x <- NULL

But I was hoping to do this with fewer commands.

Also, I know that I could drop columns using integer indexing like this:

df <- df[ -c(1, 3:6, 12) ]

But I am concerned that the relative position of my variables may change.

Given how powerful R is, I figured there might be a better way than dropping each column one by one.

Solution

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.

Answered By: Anonymous

Related Articles

  • Memcached vs. Redis?
  • AppCompat v7 r21 returning error in values.xml?
  • Octave using 'for' statement to show two animations…
  • Fix top buttons on scroll of list below
  • What is your most productive shortcut with Vim?
  • Checking if a variable is an integer in PHP
  • What is a NullReferenceException, and how do I fix it?
  • How to show title in hover - css / jquery
  • How to print binary tree diagram?
  • Is it possible to apply CSS to half of a character?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Java – Convert integer to string

Next Post:

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error