1

I am working in the development of an app for decision trees using shiny, and java script.

I have a structure of a dynamic tree, where the user can create new branchess and nodes and when the user finishes the construction of his tree, he can press a button and export the structure of the tree in a txt file.

I wonder if there is a way to avoid the button "Export to DataSet" and instead of this, load the tree in the R global environment, like a dynamic data frame.

Java Script Function to export the tree

/*
 * Print out CSV of tree: node names
 */
function printCSV() {   
    var csv = "";
    
    if (root.children) {
        
        root.children.forEach(function (d) {
            csv = csv + getCSVstring(d, "-", "", 0);
        })
    }

    var hiddenElement = document.createElement('a');

    hiddenElement.href = 'data:attachment/text,' + encodeURI(csv);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'TreeDataSet.txt';
    hiddenElement.click();

}

HTML code

<button id="exportToMatrix" onclick="printCSV();">Export To DataSet</button>

app.R

library(shiny)

server = function(input, output, session){
    
    x <- output$contents <- renderText({    
        data2 <<- read.table("exportToMatrix")
        assign(data2,envir=.GlobalEnv)
        print(summary(data))
    })
    
}

# Run the application 
shinyApp(ui = htmlTemplate("www/Tree.html"), server)

Thanks!

coding
  • 917
  • 2
  • 12
  • 25
  • If you're always running this on a console using `shinyApp`, then perhaps return a value from `runApp`? See https://stackoverflow.com/a/27366929/3358272 – r2evans Sep 29 '20 at 18:21
  • But I don't want to stop the shinyApp, because the user is going to modifying the app what I want is to load the .txt file that I generated with the function printCSV() but in the global env of RStudio.Thank you! – coding Sep 29 '20 at 18:30
  • But since the shiny app is running, you can't do anything in the global environment anyway ... so why do you need to save an intermediate value to the global environment? – r2evans Sep 29 '20 at 18:41
  • I am running the app in the background so, I think is possible now save a global variable in the RStudio env – coding Sep 29 '20 at 19:06

1 Answers1

0

On your desktop, assign can create variables from the Shiny App to .GlobalEnv, see following example:

library(shiny)

ui <- fluidPage(
  actionButton("do", "Click Me")
)

server <- function(input, output, session) {
  counter <- reactiveVal(0)
  observeEvent(input$do, {
    counter(counter()+1)
    cat('Saving object ', counter(),'\n')
    assign(paste0("test",counter()), counter(),.GlobalEnv)
    
  })
}

shinyApp(ui, server)

After each click, a new variable is created in .GlobalEnv:

Saving object  1 
Saving object  2 
Saving object  3 
Saving object  4 


> ls()
 [1] "server" "test1"  "test2"  "test3"  "test4"  "ui" 
Waldi
  • 39,242
  • 6
  • 30
  • 78