Skip to content
Back to formatted view

Raw Message

Message-ID: <a0779f14-4a1a-c79c-8760-251d00403cf9@sapo.pt>
Date: 2022-03-30T21:39:49Z
From: Rui Barradas
Subject: Creating and manipulating environment within function
In-Reply-To: <BY3PR19MB52026293CE688E35F07CBFE6CB1F9@BY3PR19MB5202.namprd19.prod.outlook.com>

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 at 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.