Is there a way that we can pass Shiny objects to embedded or outside R script? Like if I create a dateInput(let's say, ME_DATE) in ui and try to pass it in a sourced code later in server, how can it be done?
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
dateInput("ME_DATE_output",label=h2("Execution Date"), value="2020-05-29")
)))
server = function(input, output) {
ME_DATE_GUI <- reactive({input$ME_DATE_output})
Code_loc <- "K:/Codes/"
ME_DATE <<- renderPrint({ ME_DATE_GUI() })
source(paste0(Code_loc,"Passed_R_code.r"))
}
And that Passed_R_code.R starts with -
ME_DATE <- as.Date(ME_DATE, format="%Y-%m-%d")
I also tried as.character in it.
The error I get is -
Error in as.Date.default: do not know how to convert 'ME_DATE' to class “Date”
Clearly passed ME_DATE isn't taking a value in YYYY-MM-DD format but some function. I am hoping there might be a step/function to convert this.
Any help is appreciated?
I made the mistakes of not assigning ME_DATE in reactive and then not declaring source as local = TRUE-
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
dateInput("ME_DATE_output",label=h2("Execution Date"), value="2020-05-29")
)))
server = function(input, output) {
ME_DATE_GUI <- reactive({ME_DATE <-input$ME_DATE_output})
Code_loc <- "K:/Codes/"
source(paste0(Code_loc,"Passed_R_code.r"),local=TRUE)
}
I noticed the answer here - https://stackoverflow.com/a/54572066/6877763
Related
I am trying to call(source) a code based on user input date(to decide path), but can't get to execute this. There's no error, but the called(sourced) code doesn't work(I know this since no file is output). I think I am not able to use eventReactive correctly to get the code executed in following -
ui = fluidPage(
sidebarLayout(
sidebarPanel(
titlePanel("MY Outputs")
,dateInput("ME_DATE_output",label=h2("Execution Date"), value="2020-05-29")
,textOutput('dateSelectionStatement')
,hr()
,actionButton("calculate", "Calculate Again" )
,textOutput("success")
)))
server = function(input, output) {
ME_DATE_GUI <- reactive({input$ME_DATE_output})
output$dateSelectionStatement <- renderText({paste0('You have selected: ', ME_DATE_GUI()) })
Code_loc <- "K:/Codes/"
code_execution <- eventReactive(input$calculate, {source(paste0(Code_loc,"GUI_trials.r"))})
# Print a message for refresh
output$success <- renderText({paste0('Output refreshed for date - ', ME_DATE_GUI())})
}
shinyApp(ui, server)
GUI_trials look like -
# Use GUI Reactive to get the date
ME_DATE <- as.Date(ME_DATE_GUI(), format="%Y-%m-%d")
year_N_ME_DATE <- format(ME_DATE,"%Y")
month_N_ME_DATE <- format(ME_DATE,"%m")
month_T_ME_DATE <- months(ME_DATE)
# Location for Outputs
Output_DIR <- "K:/Outputs/"
Output_loc <- paste(Output_DIR,month_N_ME_DATE,". ",month_T_ME_DATE, " ",year_N_ME_DATE,"/",sep="")
success <- "Success"
write.csv(success, paste0(Output_loc,"Success.csv"))
The 2 problems are -
ME_DATE_GUI is not identified in sourced code(GUI_trials.r). Eeven if I use ME_DATE <<- renderText({input$ME_DATE_output}) in server part and place ME_DATE <- as.Date(ME_DATE, format="%Y-%m-%d") in GUI_trials.r, it's not working. The error is Error in as.Date.default: do not know how to convert 'ME_DATE' to class “Date”
eventReactive doesn't seem to do anything, i.e., actionButton part is inactive for me.
Any help is deeply appreciated!
server function as -
server = function(input, output) {
ME_DATE_GUI <- reactive({input$ME_DATE_output})
output$dateSelectionStatement <- renderText({paste0('You have selected: ', ME_DATE_GUI()) })
Code_loc <- "K:/Codes/"
observeEvent(input$calculate, {
ME_DATE <- ME_DATE_GUI()
source(paste0(Code_loc,"GUI_trials2.r"), local = TRUE)
# Print a message for refresh
output$success <- renderText({paste0('Output refreshed for date - ', ME_DATE_GUI())})
})
}
followed by change in GUI_trials2.R code as -
# Use ME_DATE from Shiny
ME_DATE <- as.Date(ME_DATE, format="%Y-%m-%d")
solved this issue!
Key was to use local=TRUE in source statement.
I have a shiny application reading an input from ui and I am unable to follow up with the data from the input in my code. As below:
ui <- fluidPage(
...
selectInput("ISvModels", "Choose:",
choices = c(1000,5000)),
)
server <- function(input, output) {
vModels <- reactive({input$ISvModels})
qtModels <- length(vModels)
qtModels
vtModels <- paste0("M",1:qtModels," n = ",vModels," scenarios")
vtModels
}
And I get:
Warning: Error in as.vector: cannot coerce type 'closure' to vector of type 'character'
I tried all sort of things from observe to renders but nothing works. Seems I'm missing some concepts here, hope you can help. Thanks!
Your server needs an output, some way for what you've calculated to be shown to the user. We can use a textOutput to achieve this.
Below is a minimal example, showing a dropdown box linked to a textbox.
library(shiny)
ui <- fluidPage(
#Dropdown
selectInput("ISvModels", "Choose:", choices = c(1000,5000)),
#Textbox
textOutput("mytext")
)
server <- function(input, output, session) {
#Prepare Textbox Content
output$mytext <- renderText({
qtModels <- length(input$ISvModels)
vtModels <- paste0("M", 1:qtModels, " n = ", input$ISvModels," scenarios")
return(vtModels)
})
}
shinyApp(ui, server)
I want to use value selected in input (below) in loop.
ui <- fluidPage(
#User dropbox
selectInput("state", "Choose state", choices=ListaKampani$Nazwa)
#Print table to UI
,tableOutput("table1")
ID_kamp <- reactive({input$state})
for (i in ID_kamp) {print(i)}
How I can use value from input as a variable in code?
In next attempt i tried this code:
library(shiny)
ui <- fluidPage(
selectInput("wyb", "Wybierz", c(1,2,3))
)
server <- function(input, output, session) {
wybor <- reactive(input$wyb)
for (a in 1:wybor()) {print(a)}
}
shinyApp(ui, server)
But i have error:
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.).
How I can make variable for loop make reactive? Reactive() function is not enough ?
I'm trying to make a simple financial calculator that is capable of converting currencies as well. I couldn't go on without quantmod, to download new information. But when I try to apply its functions in shiny, there's some problem that I couldn't make out.
library(shiny)
library(quantmod)
ui <- fluidPage(
sidebarPanel(
textInput("curr", "Currency"),
actionButton("go", "1 dollar equals to:")
),
mainPanel(
verbatimTextOutput("res")
)
)
server <- function(input, output, session) {
result <- reactiveValues(data = NULL)
observeEvent(input$go, {
getSymbols(input$curr)
result$data <- data.frame(`input$curr`)
wanted <- result$data[nrow(result$data), ncol(result$data)]
})
output$res <- renderText({
paste(wanted)
})
}
shinyApp(ui, server)
When I tried to do the same in other script, without the inputs of shiny, it worked pretty well.
When I used BRL=X as the input$curr, it should work as in the script shown below.
getSymbols("BRL=X")
data <- data.frame(`BRL=X`)
data[nrow(data),ncol(data)]
But the error message that appear says that object "input$curr" was not found.
I'm trying to figure out how to get R to interact via shiny with other javascript elements, which I'm guessing means by having server.R serve a customised shiny object (ideally json formatted?) to ui.R, which is then converted to a javascript array. My work-in-progress code is:
server.R
library(shiny)
shinyServer(
function(input, output) {
output$species_table <- renderTable({ iris[iris$Species == input$species,] })
output$json <- RJSONIO::toJSON(iris[iris$Species == input$species,], byrow=T, colNames=T) # error line
}
)
ui.R
require(shiny)
specs = as.character(unique(iris$Species))
names(specs) = specs
pageWithSidebar(
headerPanel("minimal json handling example"),
sidebarPanel(selectInput("species", "Species", specs)),
mainPanel(
tableOutput("species_table")
)
)
Which returns the server error:
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside
a reactive expression or observer.)
.. because it's obviously the wrong approach. Without server.R's line output$json <- ... the outcome works and looks like this, so the rest of the code is ok. But I also want to get the json (or any alternative format) across somehow and trigger a subsequent javascript action to read it in as an array object. Grateful for any pointers, and apologies in advance if my description is unclear.
For benefit of others this is the working formula. If anyone can suggest a more elegant solution I'd be grateful. Open the browser's javascript console log to see object 'data' being updated..
server.R
library(shiny)
iris <- datasets::iris
names(iris) <- gsub('[/.]','_',tolower(names(iris)))
shinyServer(
function(input, output) {
output$json <- reactive({
paste('<script>data=',
RJSONIO::toJSON(iris[iris$species == input$species,], byrow=T, colNames=T),
';console.log(data[0]);', # print 1 data line to console
'</script>')
})
}
)
ui.R
require(shiny)
iris <- datasets::iris
names(iris) <- gsub('[/.]','_',tolower(names(iris)))
specs <- as.character(unique(iris$species))
names(specs) <- specs
pageWithSidebar(
headerPanel("minimal json handling example"),
sidebarPanel(selectInput("species", "Species", specs)),
mainPanel(
htmlOutput("json")
)
)
So, that error generally means that you need to wrap reactive({}) around something, in this case your toJSON command. This works, and displays the JSON data.
ui.r
require(shiny)
specs = as.character(unique(iris$Species))
names(specs) = specs
pageWithSidebar(
headerPanel("minimal json handling example"),
sidebarPanel(selectInput("species", "Species", specs)),
mainPanel(
#tableOutput("species_table")
textOutput("json")
)
)
server.r
library(shiny)
shinyServer(
function(input, output) {
output$species_table <- renderTable({ iris[iris$Species == input$species,] })
output$json <-reactive({ RJSONIO::toJSON(iris[iris$Species == input$species,],
byrow=T, colNames=T) })# error line
}
)