[R] matrix to vector
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Fri May 29 21:09:23 CEST 2009
Ian Coe wrote:
> Hi,
>
> Is there a way to convert a matrix into a vector representing all
> permutations of values and column/row headings with native R functions?
> I did this with 2 nested for loops and it took about 25 minutes to run
> on a ~700x700 matrix. I'm assuming there must be a smarter way to do
> this with R's vector commands, but being new to R, I'm having trouble
> making it work.
> cbind(expand.grid(rownames(x),colnames(x)),as.vector(x))
Var1 Var2 as.vector(x)
1 d a 1
2 e a 2
3 f a 3
4 d b 4
5 e b 5
6 f b 6
7 d c 7
8 e c 8
9 f c 9
> x <- matrix(rnorm(700*700),700)
> rownames(x) <- paste("R",1:700)
> colnames(x) <- paste("C",1:700)
> system.time(foo <-
cbind(expand.grid(rownames(x),colnames(x)),as.vector(x)))
user system elapsed
1.082 0.107 1.193
>
>
> Thanks,
>
> Ian
>
>
>
> [a] [b] [c]
>
> [d] 1 4 7
>
> [e] 2 5 8
>
> [f] 3 6 9
>
>
>
> a d 1
>
> a e 2
>
> a f 3
>
> b d 4
>
> b e 5
>
> b f 6
>
> c d 7
>
> c e 8
>
> c f 9
>
>
>
>
>
>
>
>
>
> Ian Coe
>
>
>
> Connective Capital Management, LLC
>
> 385 Homer Ave.
>
> Palo Alto, CA 94301
>
> (650) 321-4826 ext. 03
>
>
>
> CONFIDENTIALITY NOTICE: This e-mail communication (inclu...{{dropped:23}}
>
> ______________________________________________
> R-help at r-project.org 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.
--
O__ ---- Peter Dalgaard Øster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list