[R] How to exclude a column by name?

Paul Hiemstra p.hiemstra at geo.uu.nl
Wed May 27 12:52:41 CEST 2009


Zeljko Vrba wrote:
> 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 :)
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>   
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

-- 
Drs. Paul Hiemstra
Department of Physical Geography
Faculty of Geosciences
University of Utrecht
Heidelberglaan 2
P.O. Box 80.115
3508 TC Utrecht
Phone:  +3130 274 3113 Mon-Tue
Phone:  +3130 253 5773 Wed-Fri
http://intamap.geo.uu.nl/~paul




More information about the R-help mailing list