Thank you! Franco ________________________________________ From: David Winsemius [dwinsem...@comcast.net] Sent: Thursday, September 29, 2011 8:09 AM To: R. Michael Weylandt <michael.weyla...@gmail.com> Cc: Mendolia, Franco; r-help@r-project.org Subject: Re: [R] Multiplying a list of matrices with a vector
On Sep 28, 2011, at 6:26 PM, R. Michael Weylandt wrote: > Untested: > > mapply('*', LL, vec) > > Those should be backticks but I can't type them on my phone Actually mapply does not require backticks since it is expecting its functions to be quoted anyway, but it didn't seem to work as you (and I) expected. > mapply('*', LL, vec) [,1] [,2] [,3] [1,] 1 2 3 [2,] 0 0 0 [3,] 0 0 0 [4,] 0 0 0 [5,] 1 2 3 [6,] 0 0 0 [7,] 0 0 0 [8,] 0 0 0 [9,] 1 2 3 What is needed is to add SIMPLIFY=FALSE > mapply('*', LL, vec, SIMPLIFY=FALSE) $A [,1] [,2] [,3] [1,] 1 0 0 [2,] 0 1 0 [3,] 0 0 1 $B [,1] [,2] [,3] [1,] 2 0 0 [2,] 0 2 0 [3,] 0 0 2 $C [,1] [,2] [,3] [1,] 3 0 0 [2,] 0 3 0 [3,] 0 0 3 -- David. > > Michael > > On Sep 28, 2011, at 6:04 PM, "Mendolia, Franco" <fmendo...@mcw.edu> > wrote: > >> Hi all! >> >> I have a list of matrices and I want to multiply the ith element of >> the list with the ith element of a another vector. That is, >> >>> LL <- list(A=diag(3),B=diag(3),C=diag(3)) >>> vec <- 1:3 >>> for(i in 1:3) >> + { >> + LL[[i]] <- LL[[i]]*vec[i] >> + } >>> LL >> $A >> [,1] [,2] [,3] >> [1,] 1 0 0 >> [2,] 0 1 0 >> [3,] 0 0 1 >> >> $B >> [,1] [,2] [,3] >> [1,] 2 0 0 >> [2,] 0 2 0 >> [3,] 0 0 2 >> >> $C >> [,1] [,2] [,3] >> [1,] 3 0 0 >> [2,] 0 3 0 >> [3,] 0 0 3 >> >> Is there another (more efficient) way of doing this without using >> loops? I found an older entry in this list with a similar problem, >> where the list elements were always multiplied with the same >> number, e.g., lapply(LL, function(x) x*3) and I was looking for >> something similar. >> >> Best, >> Franco >> ______________________________________________ >> R-help@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. > > ______________________________________________ > R-help@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. David Winsemius, MD West Hartford, CT ______________________________________________ R-help@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.