[R] convert list without same component length to matrix

arun smartpink111 at yahoo.com
Thu Nov 1 13:39:34 CET 2012


Hi,
Just to add:
Infact, there is a small difference in both the approaches.
For e.g when tested with your data 
sapply(l,`[`,1:4)
#     [,1] [,2] [,3] [,4] [,5]
#[1,]  1.0    3    4    2    3
#[2,]  2.0    4    2    4    5
#[3,]  3.7    5    5    6    7
#[4,]   NA    6    7    3    2
 sapply(l,head,4)
#[[1]]
#[1] 1.0 2.0 3.7
#
#[[2]]
#[1] 3 4 5 6
#
#[[3]]
#[1] 4 2 5 7
#
#[[4]]
#[1] 2 4 6 3
#
#[[5]]
#[1] 3 5 7 2
 sapply(sapply(l,head,4),`[`,1:4)
#     [,1] [,2] [,3] [,4] [,5]
#[1,]  1.0    3    4    2    3
#[2,]  2.0    4    2    4    5
#[3,]  3.7    5    5    6    7
#[4,]   NA    6    7    3    2
A.K.




----- Original Message -----
From: Al Ehan <aehan3616 at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Thursday, November 1, 2012 4:11 AM
Subject: [R] convert list without same component length to matrix

Hi,

I have this lame question. I want to convert a list (each with varies in
length) to matrix with same row length by eliminating vectors outside the
needed range.
For example:

l<-list(NULL)
l[[1]]=1,2,3.7
l[[2]]=3,4,5,6,3
l[[3]]=4,2,5,7
l[[4]]=2,4,6,3,2
l[[5]]=3,5,7,2


#so say I want to only have 4 rows and 5 column in my matrix (or
data.frame) and eliminating the 5th index value in l[[2]] and l[[4]]
#what is the simplest code would be? I actually have hundreds of the list
components.

thanks

    [[alternative HTML version deleted]]

______________________________________________
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.





More information about the R-help mailing list