[R] extract columns of a matrix/data frame
Kyle.
ambertk at ohsu.edu
Tue Jul 31 19:50:09 CEST 2007
You can use the grep function to obtain the column indices matching
your specified criteria. For example,
> r1<-c(1,2,3,7,1,3,2)
> r2<-c(4,5,7,8,1,4,3)
> test<-matrix(c(r1,r2),byrow=TRUE)
> colnames(test)<-c("a1","a2","b1","b2","b3","c1","c2")
> test
a1 a2 b1 b2 b3 c1 c2
[1,] 1 2 3 7 1 3 2
[2,] 4 5 7 8 1 4 3
> grep("a",(colnames(test)))
[1] 1 2
test.a<-test[,grep("a",(colnames(test)))]
test.a
a1 a2
[1,] 1 2
[2,] 4 5
On Jul 31, 2007, at 10:35 AM, yuvika wrote:
> Hello all,
>
> I have a matrix whose column names look like
>
> a1 a2 b1 b2 b3 c1 c2
> 1 2 3 7 1 3 2
> 4 6 7 8 1 4 3
>
> Now, I can have any number of a's. not just two as shown above
> and same goes for b's and c's. I need to extract all the a's
> columns and put them in another matrix, extract all b's columns and
> put them in some matrix and same goes for "c". How can I identify
> such pattern and get subsets of this matrix depending on columns
> names?
>
> I will appreciate a quick reply.
> Thanks a lot.
>
>
> ---------------------------------
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>
More information about the R-help
mailing list