[R] extract columns using their names

Eric Lecoutre lecoutre at stat.ucl.ac.be
Thu May 27 16:27:18 CEST 2004



Hello,

I dont clearly see why you have a problem... What you have to us works 
perfectly.

» mat=diag(3)
» colnames(mat)=letters[1:3]
» mat
      a b c
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
» mat[,c("a","c")]
      a c
[1,] 1 0
[2,] 0 0
[3,] 0 1

Only condition is to have *set* the names if those columns. See 'colnames' 
or 'dimnames' for that.

Eric

At 16:19 27/05/2004, you wrote:
>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

Eric Lecoutre
UCL /  Institut de Statistique
Voie du Roman Pays, 20
1348 Louvain-la-Neuve
Belgium

tel: (+32)(0)10473050
lecoutre at stat.ucl.ac.be
http://www.stat.ucl.ac.be/ISpersonnel/lecoutre

If the statistics are boring, then you've got the wrong numbers. -Edward 
Tufte




More information about the R-help mailing list