Skip to content

Passing function to tapply as a string

4 messages · Richard Cotton, Henrique Dallazuanna, Yuri Volchik +1 more

#
Yes.  This isn't exactly what you wanted, but it demonstrates the 
principle.

x = rnorm(5)
[1] -0.6510448  0.4591730  1.3225205  1.2314391 -0.0888139

myfun <- function(fname, x) eval(parse(text=paste(fname,"(x)",sep="")))
myfun('max',x)
[1] 1.322521

myfun('min',x)
[1] -0.6510448

Regards,
Richie.

Mathematical Sciences Unit
HSL


------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}
#
Or perhaps:

myfun <- function(fname, ...)match.fun(fname)(...)
On 07/03/2008, Richard.Cotton at hsl.gov.uk <Richard.Cotton at hsl.gov.uk> wrote:

  
    
2 days later
#
Thanks,

match.fun is what i was looking for :-)






Or perhaps:

myfun <- function(fname, ...)match.fun(fname)(...)
On 07/03/2008, Richard.Cotton at hsl.gov.uk <Richard.Cotton at hsl.gov.uk> wrote:

  
    
#
Also note that there is match.funfn in the gsubfn package.  That allows
you to also pass functions defined as formulas:

e.g.

library(gsubfn)
f.at.four <- function(f) match.funfn(f)(4)

f.at.four(sqrt) # 2
f.at.four("sqrt") # 2
f.at.four(~ x^.5) # 2 - uses function(x) x^.5

See homepage, ?match.funfn and the vignette.
On Mon, Mar 10, 2008 at 11:46 AM, Yuri Volchik <yuri.volchik at gmail.com> wrote: