[R] uneven list to matrix
Christopher Marcum
cmarcum at uci.edu
Fri Aug 24 05:22:53 CEST 2007
Hello,
I am sure I am not the only person with this problem.
I have a list with n elements, each consisting of a single column matrix
with different row lengths. Each row has a name ranging from A to E. Here
is an example:
alph[[1]]
A 1
B 2
C 3
D 4
alph[[2]]
A 1
C 3
D 4
alph[[3]]
A 1
D 4
E 5
I would like to create a matrix from the elements in the list with n
columns such that the row names are preserved and NAs are inserted into
the cells where the uneven lists do not match up based on their row names.
Here is an example of the desired output:
newmatrix
[,1] [,2] [,3]
A 1 1 1
B 2 NA NA
C 3 3 NA
D 4 4 4
E NA NA 5
Any suggestions?
I have tried
do.call("cbind",list)
I also thought I was on the right track when I tried converting each
element into a vector and then running this loop (which ultimately
failed):
newmat<-matrix(NA,ncol=3,nrow=5)
colnames(newmatrix)<-c(A:E)
for(j in 1:3){
for(i in 1:5){
for(k in 1:length(list[[i]])){
if(is.na(match(colnames(newmatrix),names(alph[[i]])))[j]==TRUE){
newmatrix[i,j]<-NA}
else newmatrix[i,j]<-alph[[i]][k]}}}
Thanks,
Chris
UCI Sociology
More information about the R-help
mailing list