[R] repeatedly applying function with matrix-rows as argument

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Mon Jun 30 14:22:35 CEST 2003


Maarten Speekenbrink wrote:
> Dear R-users,
> 
> Suppose I have a function which takes three arguments. I would like to repeatedly apply the function, using a matrix N*3 in which each row supplies the three argements for the function. Is this possible? Thank you for your help in advance!
> 


  You have a function foo:

 > foo
function(x1,x2,x3){x1+2*x2+3*x3}

  and a 3-column matrix 'm', then do:

 > apply(m,1,function(x){foo(x[1],x[2],x[3])})
  [1] 1.929147 4.695657 4.378048 2.716041 3.835949 4.177343 2.031089 
3.304404
  [9] 1.727687 2.204355

The trick here is to write a function(x) in-line to the apply. This 
function gets one row of the matrix at a time, and calles foo with three 
args.

  You could also write a new function, foo3:

  foo3 <- function(v){ foo(v[1],v[2],v[3])}

  and then apply that:

 > apply(m,1,foo3)
  [1] 1.929147 4.695657 4.378048 2.716041 3.835949 4.177343 2.031089 
3.304404
  [9] 1.727687 2.204355


Baz




More information about the R-help mailing list