Passing json/data to a javascript object with shiny - r

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
}
)

Related

Use reactive input into R code calculations for Shiny

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)

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.

SelectInput in Shiny

I am trying to build a simple Shiny App, but cant get it to work. I want to select a state and then the app should calculate the mean of that state for sample.measurement of ozone level. Here is my ui.R code:
require(shiny)
fluidPage(pageWithSidebar(
headerPanel("Ozone Pollution"),
sidebarPanel(
h3('State'),selectInput("inputstate","Select State",state.name)),
mainPanel(
h3('Results'),verbatimTextOutput("res")
)
))
And here is my server.R program:
require(dplyr)
library(shiny)
shinyServer(
function(input, output) {
stat_state<-reactive({filter(ozone_2015,State.Name==input$inputstate)})
output$res<- renderPrint({mean(stat_state$Sample.Measurement)})
}
)
Any Hints? Thanks.....
While I can't replicate your dataset because I don't know where ozone_2015 comes from, I think your problem is that you're not referring to "reactive" objects like this:
stat_state()
Once you make a reactive object, with the exception of reactive values and input$ variables, you need to refer to it with '()' at the end of the variable.
Here is an example using some of your code with a different dataset. Hope this helps.
require(shiny)
ui <-
fluidPage(pageWithSidebar(
headerPanel("Population"),
sidebarPanel(
h3('State'),selectInput("inputstate","Select State",state.name)),
mainPanel(
h3('Results'),verbatimTextOutput("res")
)
))
server <- function(input,output){
require(dplyr)
sample.data <- reactive({as.data.frame(state.x77)})
stat_state <- reactive({sample.data()[which(row.names(sample.data()) == input$inputstate),]})
output$res <- renderPrint({stat_state()$Population})
}
)
}
shinyApp(ui = ui, server = server)

How to embed a value from a reactive dataset in a tags() function in shiny?

In the shiny app below, I would like to print out parts of the two reactive datasets (reactiveDf and reactive2) using the function tags but the script I have is not working.
I know I could use other solutions like renderTable, but later on I need to embed this reactive code in a html page using {{}}, thus it would be wonderful if somebody can explain to me why this is not working.
library(shiny)
library(dplyr)
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
checkboxGroupInput('Category', '',
unique(mtcars$carb), selected = unique(mtcars$carb))),
# Show table of the rendered dataset
mainPanel(
tags$div(reactiveDf()),
tags$div(reactive2())
)
)
))
server <- shinyServer(function(input, output) {
reactiveDf <- reactive({return(tbl_df(mtcars) %>%
filter(carb %in% input$Category))})
reactive2 <- reactive({reactiveDf()[1,]})
})
shinyApp(ui = ui, server = server)

Shiny: Why using a temporay variable for output on the server side fails?

Here is a simple shiny app that works :
ui.R
library(shiny)
shinyUI(bootstrapPage(
numericInput("mymun", "enter a number",0),
textOutput("mytext")
))
server.R
library(shiny)
test <- function(input, output){
renderText(paste("this is my number:",input$mymun))
}
shinyServer(function(input, output) {
output$mytext <- test(input, output)
})
However if I put the result of the function call in a temporary variable the app fails
server.R
library(shiny)
test <- function(input, output){
renderText(paste("this is my number:",input$mymun))
}
shinyServer(function(input, output) {
tmp <- test(input, output)
output$mytext <- tmp
})
The error message is :
Error in substitute(value)[[2]] :
object of type 'symbol' is not subsettable
Does anyone could gives clues about why the second one fails and why the first does not ?
I guess this is due to expression processing and the reactive logic of shiny server, but I am not clear about it.
The best way to actually figure this out is to re-read http://www.rstudio.com/shiny/lessons/Lesson-6/ + http://www.rstudio.com/shiny/lessons/Lesson-7/ + http://rstudio.github.io/shiny/tutorial/#scoping to ensure you fully understand reactivity and scoping (no sense posting the seminal tutorial text in SO).
To get something close to what you're trying to do, you'd need to do the following in server.R:
library(shiny)
shinyServer(function(input, output) {
test <- reactive({
return(paste("this is my number:",input$mymun))
})
output$mytext <- renderText({
tmp <- test()
return(tmp)
})
})

Resources