[R] Strange behaviour of R?
Gabor Grothendieck
ggrothend|eck @end|ng |rom gm@||@com
Fri Jan 17 14:25:28 CET 2020
Normally one uses match.fun to avoid such problems.
This will give the error shown even if FUN is defined in the global environment.
test <- function(FUN, args) {
FUN <- match.fun(FUN)
print(FUN)
FUN(args)
}
test(NULL, 1:10)
## Error in match.fun(FUN) : 'NULL' is not a function, character or symbol
On Fri, Jan 17, 2020 at 5:41 AM Duncan Murdoch <murdoch.duncan using gmail.com> wrote:
>
> On 17/01/2020 2:33 a.m., Sigbert Klinke wrote:
> > Hi,
> >
> > I wrote a function like
> >
> > test <- function(FUN, args) {
> > print(FUN)
> > FUN(args)
> > }
> >
> > When I call it lieke this
> >
> > test(mean, 1:10)
> > test(NULL, 1:10)
> >
> > then the second call still uses mean, although I set FUN to NULL. Is
> > that ok?
>
> You probably have a function defined in your global environment that is
> named FUN and acts like mean.
>
> The general rule in R is that it only looks for objects of mode function
> when trying to find something used as a function. So in your second
> case, when trying to evaluate FUN(args), R will look for a function
> named FUN in the local evaluation frame, and won't find one: FUN is
> NULL there. Then it will go to the environment of test, which is likely
> the global environment, and look there. That's where it probably found
> the function.
>
> For example, try this:
>
> FUN <- function(...) print('FUN was called')
>
>
> test <- function(FUN, args) {
> print(FUN)
> FUN(args)
> }
>
> test(NULL, 1:10)
>
> Duncan Murdoch
>
> >
> > Actually, I used something like
> >
> > test(mean, list(x=1:10, na.rm=TRUE))
> >
> > which actually crashed R, but I can not reproduce it. Of course, when I
> > replaced FUN(args) with do.call(FUN, args) then everything works fine.
> >
> > Sigbert
> >
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list