[R] Problem of scope

Uwe Ligges ligges at statistik.tu-dortmund.de
Fri Dec 27 15:52:29 CET 2013



On 27.12.2013 15:33, Sébastien Bihorel wrote:
> Hi,
>
> I have a problem of variable scope illustrated by the following example
> (this examples greatly simplifies the actual code I am working on but I
> unfortunately cannot share it). I have two functions, funa and funb: funb
> is called within funa. The goal of funb is to modify variables created
> within funa and also perform some some action using these variables.
> Obviously, there is something wrong with this code because the variables
> aa, bb, and cc have different values when they are printed in funa or funb.
>
> I have read the section about scope in the Introduction to R manual and do
> not really understand why my code is not working. Any suggestion will be
> greatly appreciated.


If you want that funb modifies objects in the environment of funa, you 
either have to access that environment explicitly or to allow that from 
the scoping rules easily, define funb within funa, so that funa is 
funb's parent:


funa <- function(x){
   # here is some code that defines the variables aa, bb, cc
   aa <- 11
   bb <- 21
   cc <- 31
   # fun b uses some input variable of funa to modify aa, bb, and cc

   funb <- function(x){
     aa <<- pi*x
     bb <<- 5*x
     cc <<- sin(x)
     cat(sprintf('funb: aa=%s, bb=%s, cc=%s\n',aa,bb,cc))
}

   funb(x)
   cat(sprintf('funa: aa=%s, bb=%s, cc=%s\n',aa,bb,cc))
}
funa(5)


Best,
Uwe Ligges




> Thanks
>
> ##### CODE STARTS HERE ####
>
> funa <- function(x){
>    # here is some code that defines the variables aa, bb, cc
>    aa <- 11
>    bb <- 21
>    cc <- 31
>    # fun b uses some input variable of funa to modify aa, bb, and cc
>    funb(x)
>    cat(sprintf('funa: aa=%s, bb=%s, cc=%s\n',aa,bb,cc))
> }
>
> funb <- function(x){
>
>    aa <<- pi*x
>    bb <<- 5*x
>    cc <<- sin(x)
>    cat(sprintf('funb: aa=%s, bb=%s, cc=%s\n',aa,bb,cc))
>
>    # Not executed
>    # here is some code that would do something with aa, bb, and cc
>    # plot(aa,bb)
> }
>
> funa(5)
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>



More information about the R-help mailing list