[R] extract columns using their names

Dimitris Rizopoulos dimitris.rizopoulos at med.kuleuven.ac.be
Thu May 27 16:28:59 CEST 2004


Dear Adrian,

you could use something like:

x <- matrix(1:30,5,6)
colnames(x) <- letters[1:6]

your.choices <- c("a", "d", "f")
x[,match(your.choices, colnames(x))]

I hope this helps.

Best,
Dimitris

----
Dimitris Rizopoulos
Doctoral Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/16/396887
Fax: +32/16/337015
Web: http://www.med.kuleuven.ac.be/biostat/
     http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm


----- Original Message ----- 
From: "Adrian Dusa" <adi at roda.ro>
To: <r-help at stat.math.ethz.ch>
Sent: Thursday, May 27, 2004 4:19 PM
Subject: [R] extract columns using their names


> Hello,
>
> Is there a way to extract multiple columns from a dataframe using
their
> names instead of their numbers?
>
> Currently I use:
>
> data2 <- data1[, c(1,3,9)]
>
> And I am looking for something like
>
> data2 <- data1[, c("XX","YY","ZZ")]
>
>
> I use the same dataframe for many purposes, and I run codes that
change
> the order of the columns every time.
>
> Many thanks,
> Adrian
>
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> Adrian Dusa (adi at roda.ro)
> Romanian Social Data Archive (www.roda.ro)
> 1, Schitu Magureanu Bd.
> 050025 Bucharest sector 5
> Romania
> Tel./Fax: +40 (21) 312.66.18\
>               +40 (21) 312.02.10/ int.101
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html




More information about the R-help mailing list