How load a dynamic data frame in Global R environment?

558 views Asked by At

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!

1

There are 1 answers

0
Waldi On

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"