Skip to content
Back to formatted view

Raw Message

Message-ID: <3F002B8B.1070602@lancaster.ac.uk>
Date: 2003-06-30T12:22:35Z
From: Barry Rowlingson
Subject: repeatedly applying function with matrix-rows as argument
In-Reply-To: <21F67EF0AFCF3F449AF94D739A035035B515EF@rea05.fmg.uva.nl>

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