[R] extract columns using their names

Adrian Dusa adi at roda.ro
Thu May 27 16:35:49 CEST 2004


Right...

As was under the impression that, if I dind't attach the dataframe, I
have to use data1$XX, data1$YY and so on.
I tried
data2 <- data1[, c("data1$XX","data1$YY","data1$ZZ")]

I see my error now.

Thank you very much,
Adrian

-----Original Message-----
From: Eric Lecoutre [mailto:lecoutre at stat.ucl.ac.be] 
Sent: Thursday, May 27, 2004 5:27 PM
To: adi at roda.ro
Cc: r-help at stat.math.ethz.ch
Subject: Re: [R] extract columns using their names




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