[R-pkg-devel] Assigning an object to the global environment (shiny package)

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Thu Jan 4 22:06:52 CET 2024


On 04/01/2024 3:51 p.m., Tiago Olivoto wrote:
> Hi everyone!
> I which a happy new year!
> 
> 
> I'm coding a shiny app and I would like to include an option so that the
> users can assign the results to the global environment for further analysis.
> 
> I have written the following code, which checks if 'globalvarname' (the
> name of object to be created in the global environment) already exists,
> returning an error if so, and asking to the user change the name.
> 
> code
> -----------
> observeEvent(input$savetoglobalenv, {
>   ### more code here
> 
>    if (exists(input$globalvarname, envir = globalenv())) {
>      sendSweetAlert(
>        session = session,
>        title = "Error",
>        text = paste0("The object'", input$globalvarname, "' already exists
> in the global environment. Please, change the name."),
>        type = "success"
>      )
>    } else {
>      assign(input$globalvarname, report, envir = globalenv())
>      ask_confirmation(
>        inputId = "myconfirmation",
>        type = "warning",
>        title = "Close the App?",
>        text = paste0("The object'", input$globalvarname, "' has been created
> in the Global environment. To access the created object, you need first to
> stop the App. Do you really want to close the app now?"),
>        btn_labels = c("Nope", "Yep"),
>        btn_colors = c("#FE642E", "#04B404")
>      )
>    }
> })
> ---------
> 
> Thus, the object is only created when the user decides to assign such an
> object to the global environment. As the object's name is checked, there is
> no way of replacing some object already available in the global environment.
> 
> Of course, when running devtools::check(), a NOTE is returned
> 
> Found the following assignments to the global environment:
>    Arquivo 'plimanshiny/R/mod_analyze.R':
> 
> Can I ignore this safely?
> Is there any suggestion to handly this without using 'assign()'

A simple alternative would be to assign it into a private environment 
managed by your app, and supply a function to the user to retrieve it 
from there.  The user can choose where to assign the result of that 
function.

So instead of:

   user says to save to "myvar"
   you save to myvar
   user uses myvar

you would have

   user says to save value
   you save it privately
   user runs myvar <- savedvalue()

If your app requires users to be able to save several different values, 
the user could enter a name on the first line and enter it again on the 
third line.

Duncan Murdoch

Duncan Murdoch



More information about the R-package-devel mailing list