Reputation: 4194
I have a list like
$`1`
[1] 1959 13
$`2`
[1] 2280 178 13
$`3`
[1] 2612 178 13
$`4`
[1] 2902 178 13
And the structure is something like:
structure(list(`1` = c(1959, 13), `2` = c(2280, 178, 13), `3` = c(2612,
178, 13), `4` = c(2902, 178, 13)......,.Names = c("1", "2", "3", "4"....)
How can I combine the lists within this list and produce a list like:
$`list`
[1] 1959 13
[2] 2280 178 13
[3] 2612 178 13
[4] 2902 178 13
Upvotes: 0
Views: 272
Reputation: 109844
This is the closest I can get to what you're asking for as a matrix:
LIST <- structure(list(`1` = c(1959, 13), `2` = c(2280, 178, 13), `3` = c(2612,
178, 13), `4` = c(2902, 178, 13)))
cbind.fill <-
function(...) {
nm <- list(...)
nm<-lapply(nm, as.matrix)
n <- max(sapply(nm, nrow))
do.call(cbind, lapply(nm, function(x) rbind(x,
matrix(, n - nrow(x), ncol(x)))))
}
t(do.call('cbind.fill', LIST))
print(X$list, na.print="", quote=FALSE)
Or using plyr
LIST <- lapply(LIST, function(x) data.frame(t(x)))
library(plyr)
rbind.fill(LIST)
Maybe you just don't want names ?
If so...
names(LIST) <- NULL
LIST
I think I just don't get the output structure you're after.
Upvotes: 4
Reputation: 5537
Try the following code. The problem is that I'm not too sure what you want as your output; you're calling it a list but it looks an awful lot like matrix. Assuming that you do want it as a matrix, the following should do the trick:
x <- list()
x$`1` <- c(1959, 13)
x$`2` <- c(2280, 178, 13)
x$`3` <- c(2612, 178, 13)
x$`4` <- c(2902, 178, 13)
# maximum number of elements in any vector
max <- max(sapply(x, function(y) length(y)))
# make all vectors the same length
x <- lapply(x, function (y){length(y) <- max; y})
# combine them in a matrix
result <- do.call(rbind, x)
result:
> result
[,1] [,2] [,3]
1 1959 13 NA
2 2280 178 13
3 2612 178 13
4 2902 178 13
You can always save this matrix output as an element of a list. I got the idea to make the lengths equal from here.
You won't be able to get rid of the NA if you want your matrix to be numeric (you can always turn it into characters and make the NA be "", but it's probably not a good idea for further work with the matrix).
It may be that I'm confused and that you want a list after all, but as Josh mentioned in his comment, your data is correct to begin with in that case.
Upvotes: 0