[R] mapply for matrices

Berton Gunter gunter.berton at gene.com
Thu Oct 6 00:28:29 CEST 2005


At the risk of being dense or R-ically incorrect, why do it without loops
when it is natural and easy to do it with them? More to the point:

1. vectorization speeds things up

2. apply commands are basically looping, not vectorization. Their advantage
is coding transparency, not speed

Flog me if you will ...

(of course constructs like sapply(index,function(index, A,b)...,A=A,b=b )
always work -- but why bother? )

-- Bert Gunter
Genentech Non-Clinical Statistics
South San Francisco, CA
 
"The business of the statistician is to catalyze the scientific learning
process."  - George E. P. Box
 
 

> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch 
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Tamas K Papp
> Sent: Wednesday, October 05, 2005 2:37 PM
> To: R-help mailing list
> Subject: [R] mapply for matrices
> 
> Hi,
> 
> I have a matrix A and a vector b, and would like to apply a function
> f(a,b) to the rows of A and the elements of b.  Eg
> 
> A <- matrix(1:4,2,2)
> b <- c(5,7)
> f <- function(a,b) {sum(a)*b}
> 
> myapply(f,A=A,b=b)
> 
> would give
> 
> (1+3)*5 = 20
> (2+4)*7 = 42
> 
> I found mapply, but it does not work for matrices.  How could I do
> this without loops?  The above is just a toy example, the problem I am
> using this for has larger matrices, and f is a computation that does
> not handle vectors.
> 
> One thing I thought of is
> 
> sapply(seq(along=b),function(i,A,b){f(A[i,],b[i])},A=A,b=b)
> 
> but this is not very elegant.  I checked the archives and 
> found nothing.
> 
> Thank you,
> 
> Tamas
> 
> -- 
> Bayesian statistics is difficult in the sense that thinking 
> is difficult.
> --Donald A. Berry, American Statistician 51:242 (1997)
> 
> ______________________________________________
> 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
>




More information about the R-help mailing list