Maarten Speekenbrink
2003-Jun-30 12:12 UTC
[R] repeatedly applying function with matrix-rows as argument
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! Kind regards, Maarten --------------------------------------------------------------------- Maarten Speekenbrink Psychological Methodology Department of Psychology, Faculty of Social and Behavioral Sciences address: Roetersstraat 15, 1018 WB Amsterdam, Netherlands tel: +31 20 525 6876 / +31 20 525 6870 fax: +31 20 639 0026
Prof Brian Ripley
2003-Jun-30 12:20 UTC
[R] repeatedly applying function with matrix-rows as argument
apply(mymatrix, 1, function(x) myfun(x[1], x[2], x[3])) On Mon, 30 Jun 2003, Maarten Speekenbrink wrote:> 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! >-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595
Barry Rowlingson
2003-Jun-30 12:22 UTC
[R] repeatedly applying function with matrix-rows as argument
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