[R] Converting a Matrix to a Vector
Dimitris Rizopoulos
d.rizopoulos at erasmusmc.nl
Wed Mar 25 08:29:40 CET 2009
try this:
set.seed(1)
m <- matrix(runif(5^2), nrow = 5,
dimnames = list(c("A","B","C","D","E"), c("O","P","Q","R","S")))
v <- c(m)
names(v) <- paste(rownames(m), colnames(m)[col(m)], sep = ".")
# or
# names(v) <- outer(rownames(m), colnames(m), paste, sep = ".")
v
I hope it helps.
Best,
Dimitris
Ken-JP wrote:
> Say I have:
>
>> set.seed( 1 )
>> m <- matrix( runif(5^2), nrow=5, dimnames = list( c("A","B","C","D","E"),
>> c("O","P","Q","R","S") ) )
>> m
> O P Q R S
> A 0.2655087 0.89838968 0.2059746 0.4976992 0.9347052
> B 0.3721239 0.94467527 0.1765568 0.7176185 0.2121425
> C 0.5728534 0.66079779 0.6870228 0.9919061 0.6516738
> D 0.9082078 0.62911404 0.3841037 0.3800352 0.1255551
> E 0.2016819 0.06178627 0.7698414 0.7774452 0.2672207
>
> -------------------------------------------------------------------------------------------
>
> I want to create a vector v from matrix m that looks like this:
>
> A.O 0.2655087
> B.O 0.3721239
>
> v <- as.vector( m ) almost gives me what I want, but then I need to take
> combinations of colnames( m ) and rownames( m ) to get my labels and hope
> they match up in order: if not, manipulate the order. This approach feels
> kludgy...
>
> Is this the right approach or is there a better way?
>
>
>
--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center
Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
More information about the R-help
mailing list