# [R] smart way to turn a vector into a matrix

Phil Spector spector at stat.berkeley.edu
Fri Mar 26 20:07:11 CET 2010

```Anna -
Does this do what you want?

> parts = split(initialMatrix,initialMatrix[,1])
> parts = lapply(parts,function(x)matrix(x,ncol=2))
> parts
\$A
[,1] [,2]
[1,] "A"  "1"
[2,] "A"  "2"
[3,] "A"  "3"

\$B
[,1] [,2]
[1,] "B"  "1"
[2,] "B"  "2"
[3,] "B"  "3"
[4,] "B"  "4"

\$C
[,1] [,2]
[1,] "C"  "1"
[2,] "C"  "2"
[3,] "C"  "3"

- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu

On Fri, 26 Mar 2010, anna wrote:

>
> Hello guys, I am working on a matrix which looks like this one:
>> initialMatrix <-
>> rbind(cbind(rep("A",3),seq(1,3)),cbind(rep("B",4),seq(1,4)),cbind(rep("C",3),seq(1,3)))
>> initialMatrix
>      [,1] [,2]
> [1,] "A"  "1"
> [2,] "A"  "2"
> [3,] "A"  "3"
> [4,] "B"  "1"
> [5,] "B"  "2"
> [6,] "B"  "3"
> [7,] "B"  "4"
> [8,] "C"  "1"
> [9,] "C"  "2"
> [10,] "C"  "3"
>
> and I would like to turn it into a list that looks like that but don't know
> which operation to apply on it:
>> myList<-list()
>> myList[]<-cbind(rep("A",3),seq(1,3))
>> myList[]<-cbind(rep("B",4),seq(1,4))
>> myList[]<-cbind(rep("C",3),seq(1,3))
>> myList
> []
>     [,1] [,2]
> [1,] "A"  "1"
> [2,] "A"  "2"
> [3,] "A"  "3"
>
> []
>     [,1] [,2]
> [1,] "B"  "1"
> [2,] "B"  "2"
> [3,] "B"  "3"
> [4,] "B"  "4"
>
> []
>     [,1] [,2]
> [1,] "C"  "1"
> [2,] "C"  "2"
> [3,] "C"  "3"
> I thought about a using which and lapply but didn't get to a solution.
> There is always a smart way to do it I'm sure but I'm not finding it...Can
>
>
> -----
> Anna Lippel
> --
> View this message in context: http://n4.nabble.com/smart-way-to-turn-a-vector-into-a-matrix-tp1692671p1692671.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help