[R] Creating and manipulating environment within function

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Wed Mar 30 23:39:49 CEST 2022


Hello,

Use ?assign instead. And there was a bug in manipulate_e1, it would 
throw an error a not found.


create_e1 <- function(){
   assign("e1", new.env(), envir = globalenv())
   exists('e1', mode = 'environment')
}

manipulate_e1 <- function(a){
   if ( exists('e1', mode = 'environment') ) {
     assign(a, 1, envir = e1)
     TRUE
   } else {
     FALSE
   }
}

create_e1()
#> [1] TRUE

exists('e1', envir = globalenv())
#> [1] TRUE

x <- "vec"
e1$vec
#> NULL
manipulate_e1(x)
#> [1] TRUE
e1$vec
#> [1] 1


Hope this helps,

Rui Barradas

Às 21:29 de 30/03/2022, Sebastien Bihorel escreveu:
> Hi
> 
> I am trying to create a set of functions to create and manipulate objects within a dedicated environment, which I was hoping to put directly under the global environment. However, my implementation (see code below) is facing some scoping issues: the environment created by one function does not appear to be accessible from outside the function.
> 
> What would be the proper way to create a manipulation an environment in different functions?
> 
> Thanks
> 
> ```
> create_e1 <- function(){
>    e1 <- new.env(parent = globalenv())
>    exists('e1', mode = 'environment')
> }
> create_e1()
> 
> manipulate_e1 <- function(){
>    if ( exists('e1', mode = 'environment') ) {
>      assign(a, 1, envir = e1)
>      TRUE
>    } else {
>      FALSE
>    }
> }
> 
> exists('e1', envir = globalenv())
> manipulate_e1()
> ```
> This message is sent to you because your email address is the contact email address provided for receiving messages related to: our products or services purchased, or information requested, from us; and/or evaluating or having entered into a business relationship with us. Visit our privacy policy at https://www.simulations-plus.com/privacy-policy/ to learn more about how we use your personal information and your rights regarding your personal information, including how to opt out of receiving marketing emails from us.
> 
> ______________________________________________
> 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.



More information about the R-help mailing list