Skip to content
Prev 33993 / 398513 Next

repeatedly applying function with matrix-rows as argument

Maarten Speekenbrink wrote:
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