Skip to content
Back to formatted view

Raw Message

Message-ID: <16030.25110.309065.58742@gargle.gargle.HOWL>
Date: 2003-04-17T08:13:10Z
From: Martin Maechler
Subject: A function as argument of another function
In-Reply-To: <003a01c304b5$5f397aa0$5c13070a@it.giustizia.it>

>>>>> "vito" == vito muggeo <vito.muggeo at giustizia.it>
>>>>>     on Thu, 17 Apr 2003 09:45:41 +0200 writes:

(MM: I've added " " around "<-" and empty lines:)

    vito> Dear all,
    vito> I would like to write a function like:

    vito> myfun <- function(x,fn) {xx<-exp(x); x*fn(xx)}

    vito> where fn is a symbolic description of any function
    vito> with its argument to be specified. Therefore

    vito> myfun(5,"2+0.3*y^2")
    vito> should return 5*(2+0.3*exp(5)^2),

    vito> myfun(5,"log(y)") should return 5*log(exp(5)) and so on.

    vito> I tried with "expression" and others, but without
    vito> success. How can I solve my problem?

As you say yourself in the subject, the argument must be a
*function*, not a string or an expression, e.g.,  
   function(y) y^2  

is a function.  So,

  myfun <- function(x,fn) { xx <- exp(x); x*fn(xx) }
  myfun(5, function(y) 2+0.3*y^2)

gives 33049.7, as desired.

Regards,
Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/