On 09/17/2009 12:04 PM, Martin Maechler wrote:

"SH" == Schalk Heunis<schalk.heu...@enerweb.co.za>
     on Thu, 17 Sep 2009 11:15:16 +0200 writes:

     SH>  I think this is what you want:
     >>  df<- data.frame(x1=1:11,x2=2:12,x3=3:13,y=4:14)
     >>  grep('^x',names(df))
     SH>  [1] 1 2 3

     SH>  The returned indexes refer to the column positions, so you could do:
     >>  names(df)[grep('^x',names(df))]
     SH>  [1] "x1" "x2" "x3"

yes, or slightly more elegant and efficient

   >  grep('^x',names(df), value = TRUE)
   [1] "x1" "x2" "x3"

or, if you have the operators package:

> require( operators )
> names(df) %~|% "^x"
[1] "x1" "x2" "x3"

... note that is has been declared confusing in this mailing list previously. http://article.gmane.org/gmane.comp.lang.r.general/154749



     SH>  or
     >>  df[,grep('^x',names(df))]
     SH>  x1 x2 x3
     SH>  1   1  2  3
     SH>  2   2  3  4
     SH>  3   3  4  5
     SH>  4   4  5  6
     SH>  5   5  6  7
     SH>  6   6  7  8
     SH>  7   7  8  9
     SH>  8   8  9 10
     SH>  9   9 10 11
     SH>  10 10 11 12
     SH>  11 11 12 13

     SH>  HTH

     SH>  Schalk Heunis


     SH>  On Thu, Sep 17, 2009 at 5:03 AM, Peng Yu<pengyu...@gmail.com>  wrote:

     >>  Hi,
     >>
     >>  data.frame(x1=1:11,x2=2:12,x3=3:13,y=4:14)
     >>
     >>  I want to extract all the columns that with the name 'x?'. Is there a
     >>  general way to do this in R?
     >>
     >>  Regards,
     >>  Peng



--
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://tr.im/yw8E : New R package : sos
|- http://tr.im/y8y0 : search the graph gallery from R
`- http://tr.im/y8wY : new R package : ant

______________________________________________
R-help@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.

Reply via email to