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.
mymat <- matrix(runif(60), ncol=6) colnames(mymat) <- c("a1","a2","b1","b2","c1","c2") mymat a1 a2 b1 b2 c1 c2 [1,] 0.73623481 0.25204019 0.332436396 0.36629507 0.39517285 0.62491949 [2,] 0.48867382 0.20933245 0.511805497 0.03142542 0.82168732 0.20550784 [3,] 0.89198874 0.24477456 0.629644977 0.23442137 0.17828551 0.29640615 [4,] 0.99222414 0.49044514 0.571213786 0.91068115 0.09484414 0.78108139 [5,] 0.66615787 0.13183354 0.004350679 0.32443025 0.38742483 0.76044740 [6,] 0.06642704 0.96257552 0.189716240 0.83969989 0.53470898 0.28319039 [7,] 0.31172264 0.20201281 0.577353264 0.62082694 0.31649255 0.40977000 [8,] 0.52890283 0.46576510 0.107363256 0.72534897 0.12038182 0.06295499 [9,] 0.55292555 0.76459699 0.212533012 0.73275529 0.98008863 0.85302931 [10,] 0.84320369 0.09958472 0.158443155 0.92321443 0.50935938 0.08514859 mymat[,grep("^a", colnames(mymat))] a1 a2 [1,] 0.73623481 0.25204019 [2,] 0.48867382 0.20933245 [3,] 0.89198874 0.24477456 [4,] 0.99222414 0.49044514 [5,] 0.66615787 0.13183354 [6,] 0.06642704 0.96257552 [7,] 0.31172264 0.20201281 [8,] 0.52890283 0.46576510 [9,] 0.55292555 0.76459699 [10,] 0.84320369 0.09958472 ?grep > --------------------------------- > > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@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. -- Chuck Cleland, Ph.D. NDRI, Inc. 71 West 23rd Street, 8th floor New York, NY 10010 tel: (212) 845-4495 (Tu, Th) tel: (732) 512-0171 (M, W, F) fax: (917) 438-0894 ______________________________________________ R-help@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.