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))
[1] 1 2 3

The returned indexes refer to the column positions, so you could do:
>names(df)[grep('^x',names(df))]
[1] "x1" "x2" "x3"
or
>df[,grep('^x',names(df))]
   x1 x2 x3
1   1  2  3
2   2  3  4
3   3  4  5
4   4  5  6
5   5  6  7
6   6  7  8
7   7  8  9
8   8  9 10
9   9 10 11
10 10 11 12
11 11 12 13

HTH

Schalk Heunis


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
>
> ______________________________________________
> 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.
>

        [[alternative HTML version deleted]]

______________________________________________
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