[R] How to exclude a column by name?
Peter Dalgaard
P.Dalgaard at biostat.ku.dk
Wed May 27 13:08:26 CEST 2009
Paul Hiemstra wrote:
> 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")]
>
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))
--
O__ ---- Peter Dalgaard Øster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list