Skip to content

How to exclude a column by name?

9 messages · Paul Hiemstra, Linlin Yan, Zeljko Vrba +5 more

#
Given an arbitrary data frame, it is easy to exclude a column given its index:
df[,-2].  How to do the same thing given the column name?  A naive attempt
df[,-"name"] did not work :)
#
Zeljko Vrba wrote:
Hi,

This piece of code does the trick. Most important is the which() command:

df = data.frame(a = runif(10), b = runif(10))
df[,-which(names(df) == "a")]

cheers,
Paul
#
Hope this helps:
X1 X2 X3 X4 X5
1  1  3  5  7  9
2  2  4  6  8 10
X1 X3 X4 X5
1  1  5  7  9
2  2  6  8 10
X1 X3 X4 X5
1  1  5  7  9
2  2  6  8 10
On Wed, May 27, 2009 at 6:37 PM, Zeljko Vrba <zvrba at ifi.uio.no> wrote:
#
On Wed, May 27, 2009 at 12:52:41PM +0200, Paul Hiemstra wrote:
Thanks to you and Linlin.  It did not occur to me to use which(); I thought
that there would be a shorter way to accomplish this since names are
first-class indices for data frames and arrays.  (Or are they?  What happens
under the hood when I write df[,"a"]?)
#
Paul Hiemstra wrote:
You don't actually need which() (and the approach runs into problems if
"a" isn't there). Just select the others:

df[, names(df) != "a"]

Or, BTW, you can use within()

aq <- within(airquality, rm(Day))
#
Peter Dalgaard <P.Dalgaard <at> biostat.ku.dk> writes:
Please add this as an example to the docs of within. 

Dieter
#
Dieter Menne wrote:
possibly with the slightly more generic

    unwanted <- 'Day'
    aq <- within(airquality, rm(list=unwanted))

vQ