[R] mapply for matrices

From: Tamas K Papp <tpapp_at_princeton.edu>
Date: Thu 06 Oct 2005 - 07:36:43 EST


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}


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


but this is not very elegant. I checked the archives and found nothing.

Thank you,


Bayesian statistics is difficult in the sense that thinking is difficult.
--Donald A. Berry, American Statistician 51:242 (1997)

R-help@stat.math.ethz.ch mailing list
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Received on Thu Oct 06 07:41:52 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:40:36 EST