I have created the following reprex which tries to use a reaction function price() outside the shiny app. If i use df<-5 then the code works but when i use df<- price() the code does not work. I have a huge shiny app where i want to source() a huge script outside the shiny app but it takes some input values from a reactive function.
library(shiny)
df<-price()
ui <- fluidPage(
numericInput("price", "Price", value=1, min=1 , max=10)
,textOutput("text")
)
server <- function(input, output, session) {
price <- reactive({as.numeric(input$price)})
output$text<- renderText(df)
}
shinyApp(ui, server)
I dont want to call the script inside the app because i will have to call it again and again in every sort of output and the script is a simulation which means it changes values each time it is called. I only want to call it once so the values remain the same and i can output them.
Trying to use the suggestion by gdevaux. When i try to input the values which come out of a function in a variable it doesnt seem to work. It says 'Error in myfunction(argument1) : object 'argument1' not found '.
library(shiny)
# in script.R
myfunction <- function(argument1){
return(as.numeric(argument1))
}
f<-myfunction(argument1) #Trying to put output values in a variable
# in app.R
#source("script.R")
ui <- fluidPage(
numericInput("price", "Price", value=1, min=1 , max=10)
,textOutput("text")
)
server <- function(input, output, session) {
price <- reactive(myfunction(argument1 = input$price))
output$text<- renderText(price())
}
shinyApp(ui, server)
CodePudding user response:
You cannot define a function in the server (or ui) and then use it outside, nor call inputs values outside of a shiny app. What you can do is write your functions outside of the server (in another file for example), source it, and pass your inputs or reactive as arguments to these functions
library(shiny)
# in script.R
myfunction <- function(argument1){
return(as.numeric(argument1))
}
# in app.R
#source("script.R")
ui <- fluidPage(
numericInput("price", "Price", value=1, min=1 , max=10)
,textOutput("text")
)
server <- function(input, output, session) {
price <- reactive(myfunction(argument1 = input$price))
output$text<- renderText(price())
}
shinyApp(ui, server)