[18660] in s-news-athena
[S] Summary - Alternative to rbind
daemon@ATHENA.MIT.EDU (Kenneth H. Brown)
Sun Jul 18 14:20:48 1999
Date: Sun, 18 Jul 1999 13:17:18 -0500
From: "Kenneth H. Brown" <ken.brown@uni.edu>
To: s-news@wubios.wustl.edu
Message-Id: <37921A2E.2E7840AD@uni.edu>
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Thanks to all that replied to my request for an alternative to rbind!
Essentially the question asked how to take a list in which each element
is a matrix (different # rows, same # columns) and stack them as rbind
does. The list has 100 matrices, each with approximately 150 columns
and 100 rows. I received numerous replies with three distinct solutions.
Solution 1: Use do.call("rbind", x)
This is faster than looping over the elements of the list with rbind.
It cut the time by approximately 60%.
Solution 2: Use f <- function(x) matrix(unlist(lapply(x,t)),
ncol=ncol(x[[1]]), byrow=T)
This is faster than Solution 1. However, because (I assume) this
function must transpose each matrix in the original list, it still takes
some time to finish. I'd estimate it cut the time by 90%.
Solution 3: Use
f3<-function(x)
{
nc <- ncol(x[[1]])
nr <- sum(unlist(lapply(x, nrow)))
t(array(unlist(lapply(x, t)), c(nc, nr)))
}
This is faster than Solution 2, according to Bill Dunlap because we use
'array' here rather than 'matrix' and use one less copy of the input
data. Again, still not as fast as it could be because it must transpose
each matrix in the original list. Cut the time by about 95%.
Solution 4: This solution was implied by many respondents. Have the
function that creates the original list of matrices return the transpose
of the matrix rather than the matrix itself and then we can avoid this
step in Solution 2 and Solution 3. This was easily the fastest, adding
only a slight bit of time when creating the original list. The 'rbind'
step is now nearly instantaneous using Solution 3.
Again, thank you very much to all who replied. Your help is greatly
appreciated!
KB
--
Ken Brown
University of Northern Iowa
Department of Economics
Cedar Falls, IA 50614-0129
"Give a man a fish, feed him for a day;
Teach a man to fish, feed him for a lifetime."
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news