Skip to content

selecting matrix cels by two factors

2 messages · Dimitri Szerman, Bert Gunter

#
Hi,

I have a (numeric) matrix X of the type

 > X <- matrix(c(1:9),ncol=3,nrow=3)
 > colnames(X) <- c("A","B","C")
 > rownames(X) <- c("D","E","F")

Also, a have a data frame Y like

 > Y <- as.data.frame(cbind(	c("D","E","F","D","E","F"),
+				c("A","C","A","B","B","C") ) )

I want a matrix like

1 4	  		 X["D","A"] X["D","B"]
8 5  or, equivalentely,  X["E","C"] X["E","B"]
3 9			 X["F","A"] X["F","C"]


Any suggestions?
Thanks in advanced,

Dimitri
#
You can subscript any arbitrary array (of any dim) with an appropriately
dimensioned matrix of integer indices. So all you have to do is convert the
dimnames into indices. One simple way to do this is:

X[cbind(match(c("D","E","F","D","E","F"),rownames(X)),
	match(c("A","C","A","B","B","C"),colnames(X)))]

This gives a vector, which you can dimension however you like.

-- Bert Gunter
Genentech Non-Clinical Statistics
South San Francisco, CA
 
"The business of the statistician is to catalyze the scientific learning
process."  - George E. P. Box