[R] List to matrix or to vectors conversion
Dan davison
davison at stats.ox.ac.uk
Fri Feb 12 16:55:38 CET 2010
<Ted.Harding <at> manchester.ac.uk> writes:
>
> On 12-Feb-10 13:14:29, Juan Tomas Sayago wrote:
> > Dear list,
> > I have a list with 1000 x1000 lines and columns
Lists have neither lines nor columns. Can you explain exactly what you have?
E.g. show us the code that created your "list"?
> do you know how I can
> > convert it to matrrix or data.frame.
> > Thanks.
> > Juan
>
> as.data.frame() will convert it to a dataframe. If you then apply
> as.matrix() to the result you will get a matrix:
>
> L <- list(X=c(1,2,3),Y=c(4,5,6),Z=c(7,8,9))
If you want a matrix as opposed to a data.frame (e.g. your list entries are all
numeric), and the data set is large, this more efficient method might be useful:
> matrix(unlist(L), nrow=3)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
If it's not obvious to you what that does, consider:
> unlist(L)
X1 X2 X3 Y1 Y2 Y3 Z1 Z2 Z3
1 2 3 4 5 6 7 8 9
> matrix(unlist(L), nrow=3, byrow=TRUE)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
> matrix(unlist(L), nrow=3, byrow=FALSE)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> L
> # $X
> # [1] 1 2 3
> # $Y
> # [1] 4 5 6
> # $Z
> # [1] 7 8 9
>
> D <- as.data.frame(L)
> D
> # X Y Z
> # 1 1 4 7
> # 2 2 5 8
> # 3 3 6 9
>
> M <- as.matrix(D)
> M
> # X Y Z
> # [1,] 1 4 7
> # [2,] 2 5 8
> # [3,] 3 6 9
>
> Note that applying as.matrix() directly to the original L will
> not work. It returns a list, not a matrix.
>
> Ted.
>
> --------------------------------------------------------------------
> E-Mail: (Ted Harding) <Ted.Harding <at> manchester.ac.uk>
> Fax-to-email: +44 (0)870 094 0861
> Date: 12-Feb-10 Time: 13:40:32
> ------------------------------ XFMail ------------------------------
>
>
More information about the R-help
mailing list