Hi group! Suppose I have 2 matrices A and B of equal dimensions. I want to apply a function f to all corresponding pairs of rows from A and B in an efficient manner. Basically, I want mapply(f, data.frame(A), data.frame(B)) but for rows. How do I do it? Thanks, Andrey
A relatively simple solutions is sapply(seq(length=nrow(A)), function(x) f(A[x,], B[x,])) but I'm looking forward to see anything cleaner/simpler, Gabor On Tue, Oct 21, 2008 at 8:58 AM, cmr.Pent at gmail.com <cmr.Pent at gmail.com> wrote:> Hi group! > > Suppose I have 2 matrices A and B of equal dimensions. > I want to apply a function f to all corresponding pairs of rows from A > and B in an efficient manner. > Basically, I want > > mapply(f, data.frame(A), data.frame(B)) > > but for rows. > > How do I do it? > > Thanks, > Andrey > > ______________________________________________ > 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. >-- Gabor Csardi <Gabor.Csardi at unil.ch> UNIL DGM
cmr.Pent at gmail.com wrote:> Hi group! > > Suppose I have 2 matrices A and B of equal dimensions. > I want to apply a function f to all corresponding pairs of rows from A > and B in an efficient manner. > Basically, I want > > mapply(f, data.frame(A), data.frame(B)) > > but for rows. > > How do I do it? > >Transpose them? Or, back to basics: sapply(1:nrow(A), function(i) f(A[i,],B[i,]) ) -- O__ ---- Peter Dalgaard ?ster Farimagsgade 5, Entr.B c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
Thanks for the replies!> sapply(1:nrow(A), function(i) f(A[i,],B[i,]) ) >Actually, this solution is even slower than the explicit for-loop :-( Andrey
On Tue, Oct 21, 2008 at 1:58 AM, cmr.Pent at gmail.com <cmr.Pent at gmail.com> wrote:> Hi group! > > Suppose I have 2 matrices A and B of equal dimensions. > I want to apply a function f to all corresponding pairs of rows from A > and B in an efficient manner. > Basically, I want > > mapply(f, data.frame(A), data.frame(B)) > > but for rows.You could make a 3d array: A <- matrix(sample(100), 10) B <- matrix(sample(100), 10) library(abind) AB <- abind(A, B, rev.along = 0) apply(AB, 1, myfunction) Hadley -- http://had.co.nz/