Use reactive input into R code calculations for Shiny - r

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)

Related

How to efficiently subset a dataframe in R Shiny?

In the below example code I reactively subset the mtcars dataframe inside the renderPlot() function. However, in my larger App with many render functions in the server section I am having to repeat the same rv$x[1:input$samples], etc., over and over in many places. How would I apply this subsetting instead "at the top", into the rv <- reactiveValues(...) function itself or equivalent "master function"? I tried subsetting inside the reactiveValues() and got the message "Warning: Error in : Can't access reactive value 'samples' outside of reactive consumer. Do you need to wrap inside reactive() or observer()?" I assumed incorrectly that the reactiveValues() function is a "reactive consumer".
If someone can answer this basic understanding question, please explain the logic for correctly subsetting "at the top" because I am getting very embarrassed by my repeated questions about Shiny reactivity.
library(shiny)
ui <- fluidPage(
sliderInput('samples','Nbr of samples:',min=2,max=32,value=16),
plotOutput("p")
)
server <- function(input, output, session) {
rv <- reactiveValues(
x = mtcars$mpg,
y = mtcars$wt
)
output$p <- renderPlot({plot(rv$x[1:input$samples],rv$y[1:input$samples])})
}
shinyApp(ui, server)
There are multiple ways you can handle this.
Here is one way to create new subset reactive values inside observe.
library(shiny)
ui <- fluidPage(
sliderInput('samples','Nbr of samples:',min=2,max=32,value=16),
plotOutput("p")
)
server <- function(input, output, session) {
rv <- reactiveValues(
x = mtcars$mpg,
y = mtcars$wt
)
observe({
rv$x_sub <- rv$x[1:input$samples]
rv$y_sub <- rv$y[1:input$samples]
})
output$p <- renderPlot({plot(rv$x_sub,rv$y_sub)})
}
shinyApp(ui, server)
I'd use reactiveValues only if you need them to be modified in different places.
reactive is shiny's basic solution for this:
library(shiny)
library(datasets)
ui <- fluidPage(
sliderInput(
'samples',
'Nbr of samples:',
min = 2,
max = 32,
value = 16
),
plotOutput("p")
)
server <- function(input, output, session) {
reactive_mtcars <- reactive({mtcars[1:input$samples,]})
output$p <- renderPlot({
plot(reactive_mtcars()$mpg, reactive_mtcars()$wt)
})
}
shinyApp(ui, server)

Text output for mutually exclusive radio buttons R Shiny

Overall context: I am trying to build a decision tree app in shiny and have never used shiny before. I am trying to have text display when a certain radio button is selected. After trial and error I still can't get anything to display with different inputs. Below is the basic code.
library(shiny)
priceChange <- "Does it change the price?"
zpInfer1 <- "Can zero-price-change be inferred?"
ui <- fluidPage(
radioButtons("exist", "Does it exist?",
c("Yes" = "existYes",
"No" = "existNo"),
textOutput("a")
)
)
server <- function(input, output){
output$a <- renderText({
existAnswer <- switch(input$exist,
existYes = priceChange,
existNo = zpInfer1)
})
}
shinyApp(ui, server)
As #Phil said, this seems to be a simple syntax error. This one should work :
library(shiny)
priceChange <- "Does it change the price?"
zpInfer1 <- "Can zero-price-change be inferred?"
ui <- fluidPage(
radioButtons("exist", "Does it exist?",
c("Yes" = "existYes",
"No" = "existNo")),
textOutput("a")
)
server <- function(input, output){
output$a <- renderText({
existAnswer <- switch(input$exist,
existYes = priceChange,
existNo = zpInfer1)
})
}
shinyApp(ui, server)

Passing Shiny Object to R script

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

Error when trying to use a input value as the name of the data frame that I downloaded

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.

How can I concatenate non-reactive values with reactive value for a graph title? R Shiny

I am having trouble naming a graph title that contains a normal string AND reactive value/s.
I'm trying to do something like this:
main = "Examination of: " + input$userInput
The error message is: non-numeric argument to binary operator. Does anyone know how to fix this?
The below code could give you what you needed.
library(shiny)
ui <- basicPage(
uiOutput("test"),
plotOutput("plot1")
)
server <- function(input, output) {
output$test <- renderUI({
selectInput("dummy", "Select one value", c(mtcars$qsec))
})
output$plot1 <- renderPlot({
plot(mtcars$wt, mtcars$mpg, main = paste0("this is main ",input$dummy,""))
})
}
shinyApp(ui, server)
The usage of selectInput is for testing your requirement. Make the needful changes for your actual problem.

Resources