[R] uneven list to matrix

Gabor Grothendieck ggrothendieck at gmail.com
Fri Aug 24 06:05:55 CEST 2007


Here are two solutions.  The first repeatedly uses merge and the
second creates a zoo object from each alph component whose time
index consists of the row labels and uses zoo's multiway merge to
merge them.

# test data
m <- matrix(1:5, 5, dimnames = list(LETTERS[1:5], NULL))
alph <- list(m[1:4,,drop=F], m[c(1,3,4),,drop=F], m[c(1,4,5),,drop=F])
alph

# solution 1
out <- alph[[1]]
for(i in 2:length(alph)) {
	out <- merge(out, alph[[i]], by = 0, all = TRUE)
	row.names(out) <- out[[1]]
	out <- out[-1]
}
matrix(as.matrix(out), nrow(out), dimnames=list(rownames(out),NULL))

# solution 2
library(zoo)
z <- do.call(merge, lapply(alph, function(x) zoo(c(x), rownames(x))))
matrix(coredata(z), nrow(z), dimnames=list(time(z),NULL))


On 8/23/07, Christopher Marcum <cmarcum at uci.edu> wrote:
> 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
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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