Re: [R] Define "local" function

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Sat 16 Apr 2005 - 02:40:15 EST

You can embed your function in another:

f <- function(x) { f <- function(x) y; environment(f) <- NULL; f(x) }

On 4/15/05, Ales Ziberna <ales.ziberna@guest.arnes.si> wrote:
> I am also very interested how this could be done, possibly in such a way
> that this would be incorporated in the function itself and there wouldn't be
> a need to write "environment(f) <- NULL" before calling a function, as is
> proposed in the reply below and in a thread a few days ago!
>
> Thanks for any suggestions,
> Ales Ziberna
>
> ----- Original Message -----
> From: "Gabor Grothendieck" <ggrothendieck@gmail.com>
> To: <fsaldanha@alum.mit.edu>
> Cc: "Submissions to R help" <r-help@stat.math.ethz.ch>
> Sent: Friday, April 15, 2005 5:05 PM
> Subject: Re: [R] Define "local" function
>
> > On 4/15/05, Fernando Saldanha <fsaldan1@gmail.com> wrote:
> >> I discovered a bug in a program I am writing which was due to the
> >> program using a global variable within a function.
> >>
> >> For example,
> >>
> >> myfunc <- function(x) { y}
> >>
> >> That is, I made a mistake when defining the function and wrote "y"
> >> when I should have written "x".
> >>
> >> However, there was a variable y in the global environment and the
> >> function "worked" but gave the wrong answer.
> >>
> >> I would like to avoid this problem by defining a "local" function.
> >> That would mean a function that only accepts as variables those that
> >> were defined within its body or were passed as parameters, and would
> >> generate an error when I try to define it if I am using an "external"
> >> variable. Something like:
> >>
> >> > myfunc <- function(x, type = 'local') { y}
> >> Error: using external variable
> >>
> >> I read the documentation about environments (I still do not understand
> >> a lot of it, have been working with R for four days now), and searched
> >> the newsgroups, but I could not find the way to do this.
> >>
> >> Thanks for any suggestions.
> >>
> >
> > Try this:
> >
> >> y <- 3
> >> f <- function(x) y
> >> environment(f) <- NULL
> >> f(1)
> > Error in f(1) : Object "y" not found
> >
> > ______________________________________________
> > R-help@stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide!
> > http://www.R-project.org/posting-guide.html
> >
> >
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sat Apr 16 02:51:53 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:12 EST