selecting matrix cels by two factors

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

selecting matrix cels by two factors

Dimitri Szerman-2
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

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Reply | Threaded
Open this post in threaded view
|

Re: selecting matrix cels by two factors

Bert Gunter
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
 
 

> -----Original Message-----
> From: [hidden email]
> [mailto:[hidden email]] On Behalf Of Dimitri Joe
> Sent: Friday, December 16, 2005 3:02 PM
> To: R-Help
> Subject: [R] selecting matrix cels by two factors
>
> 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
>
> ______________________________________________
> [hidden email] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html