Reputation: 185
I'm working on a shiny app where the user input from the UI-end is used as a variable in a sourced R script.
This is the desired output. When the check-box is checked it is displayed in a table in the app:
library(shiny)
library(DT)
ui <- fluidPage(
checkboxInput("somevalue", "Check box", FALSE),
dataTableOutput("table1")
)
server <- function(input, output) {
output$table1 <- renderDataTable({
data.frame("Is the check box checked?" = input$somevalue, check.names = F)
})
}
shinyApp(ui, server)
However, when df is sourced from another R script using the value from the UI input, the app shows "Error, object foo not found". It seems like the sourced script can't read the variables in shiny's environment. How do I send variables from shiny to my sourced script?
I would like the below code to work:
# sourced script saved at ~/path/to/file/test.R
df = data.frame("Is the check box checked?" = foo, check.names = F)
App:
library(shiny)
library(DT)
ui <- fluidPage(
checkboxInput("somevalue", "Check box", FALSE),
dataTableOutput("table1")
)
server <- function(input, output) {
output$table1 <- renderDataTable({
foo <- input$somevalue
source("~/path/to/file/test.R")
df
})
}
shinyApp(ui, server)
Upvotes: 2
Views: 984
Reputation: 13
Try using:
source("~/path/to/file/test.R", local = True)
Found something similar that might give more idea. discussion
Upvotes: 0
Reputation: 185
I found the super simple answer to this question through stackoverflow's genius "Similar questions"-feature and this answer: In Shiny, update DataTable with new values from user input. I thought I would share this question anyway since I googled the question without coming across the solution to this specific problem.
Answer: To export a variable from shiny's environment to the global environment (readable by the sourced script) use <<- in variable assignment instead of <-
# sourced script saved at ~/path/to/file/test.R
df = data.frame("Is the check box checked?" = foo, check.names = F)
Functioning App:
library(shiny)
library(DT)
ui <- fluidPage(
checkboxInput("somevalue", "Check box", FALSE),
dataTableOutput("table1")
)
server <- function(input, output) {
output$table1 <- renderDataTable({
foo <<- input$somevalue
source("~/path/to/file/test.R")
df
})
}
shinyApp(ui, server)
Upvotes: 3