[R] extract same columns and rows in two matrices

Petr Savicky savicky at cs.cas.cz
Wed Mar 7 17:18:58 CET 2012


On Wed, Mar 07, 2012 at 09:00:14AM -0700, Ben quant wrote:
> Hello,
> 
> I have two matrices. They both have different row names and column names,
> but they have some common row names and column names. The row names and
> column names that are the same are what I am interested in. I also want the
> columns in the two matrices aligned the same. In the end, I need to do
> rd[1,1] and ua[1,1], for example and be accessing the same column and row
> for both matrices.  Thank you very much for all you help.
> 
> I can do it, but I am pretty sure there is a better/faster way:
> 
> ################ make some sample data
> ua = matrix(c(1,2,3,4,5,6),nrow=2,ncol=3)
> colnames(ua) = c('a','b','c')
> rownames(ua)= c('ra','rb')
> rd1 = matrix(c(7,8,9,10,11,12,13,14,15,16,17,18),nrow=3,ncol=4)
> colnames(rd1) = c('c','b','a','d')
> rownames(rd1)= c('rc','rb','ra')
> 
> > rd1
> c  b  a  d
> rc 7 10 13 16
> rb 8 11 14 17
> ra 9 12 15 18
> > ua
> a b c
> ra 1 3 5
> rb 2 4 6
> 
> ##################### get common columns and rows and order them the same,
> this works but is slow'ish
> rd1_cn = colnames(rd1)
> ua_cn = colnames(ua)
> common_t = merge(rd1_cn,ua_cn,by.x=1,by.y=1)
> common_t = as.character(common_t[,1])

Hi.

Try the following instead of merge().

  common_t = intersect(rd1_cn, ua_cn)

or

  common_t = sort(intersect(rd1_cn, ua_cn))

Petr Savicky.



More information about the R-help mailing list