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)
Related
Shiny beginner here: I want to load a different dataset depending on which action-button gets clicked on. Since the processing from there on will be the same for any dataset, I want to store them in the same reactive expression, here dataset().
See my code:
library(shiny)
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("gohere", "dataset1"),
actionButton("gothere", "dataset2")
),
mainPanel(
tableOutput("dataset")
),
)
)
)
server <- function(input, output) {
dataset <- eventReactive(input$gohere, {
mtcars
})
dataset <- eventReactive(input$gothere, {
cars
})
output$dataset <- renderTable({
dataset()
})
}
shinyApp(ui = ui, server = server)
I expect this code to load mtcars into dataset when actionButton "gohere" is clicked and proceed with renderTable and to load cars into dataset when actionButton "gothere" is clicked and proceed likewise.
However: If I click actionButton "gothere" everything works as expected, if I click "gohere" nothing happens. If I change the order of "gohere" and "gothere" inside the server- function it's the other way around.
What does the second eventReactive() do with dataset that completly invalidates the first eventReactive() ?
EDIT: And if it is overwriting it, what is it overwriting it with?
This works like ordinary R programming: your two reactive conductors are R objects with the same name, so the second one overwrites the first one.
You can use a reactive value and some observers:
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("gohere", "dataset1"),
actionButton("gothere", "dataset2")
),
mainPanel(
tableOutput("dataset")
),
)
)
server <- function(input, output) {
dataset <- reactiveVal(mtcars)
observeEvent(input$gohere, {
dataset(mtcars)
})
observeEvent(input$gothere, {
dataset(cars)
})
output$dataset <- renderTable({
dataset()
})
}
shinyApp(ui = ui, server = server)
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)
I have a shiny code like in the below. I need to define variables as reactiveValues to be updatable (or I could define them I think as global but then I have to press clean objects from Rstudio which is not very user-friendly).I try to run a validate code to check for existence of the data I have defined as reactiveValues. validate(need(exists("GSEmRNA$d"),message="Dataframe not found")) yields "Dataframe not found" thus, does not plot my boxplot. If I define them as global variables and forget to press clean objects, code might mix up as old data can be passed as if it is new. Any help is appreciated.
server.R
shinyServer(function(input, output) {
observeEvent(input$GoButton,{
dataset <- data.frame(first= c(1,5,9),second=c(8,5,13), third=c(10,3,17))
GSEmRNA <- reactiveValues(d=dataset)
})
output$BoxplotDataset <- renderPlot({
if (input$GoButton== 0) {return()}
else{
validate(need(exists("GSEmRNA$d"),message="Dataframe not found"))
boxplot(GSEmRNA$d)}
})
})
ui.R
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Dataset Selection"),
sidebarPanel(
actionButton("GoButton","GO")
),
mainPanel(
wellPanel(
column(8, plotOutput("BoxplotDataset")
)
)
)))
FOR THE RECORD, I ALSO POSTED THIS QUESTION TO SHINY GOOGLE DISCUSS GROUP https://groups.google.com/forum/#!topic/shiny-discuss/ZV5F6Yy-kFg
Here are the updated code. The points are:
library(shiny)
server <-shinyServer(function(input, output) {
GSEmRNA <- reactiveValues(d=NULL) #define it ouside
observeEvent(input$GoButton,{
dataset <- data.frame(first= c(1,5,9),second=c(8,5,13), third=c(10,3,17))
GSEmRNA$d <- dataset #assign it inside
})
output$BoxplotDataset <- renderPlot({
validate(need(GSEmRNA$d,"Dataframe not found")) # changed as well
boxplot(GSEmRNA$d)
})
})
ui <- pageWithSidebar(
headerPanel("Dataset Selection"),
sidebarPanel(
actionButton("GoButton","GO")
),
mainPanel(
wellPanel(
column(8, plotOutput("BoxplotDataset")
)
)
))
runApp(list(ui=ui,server=server))
Defined the reactiveValues outside of the observeEvent
Changed the reactiveValues inside of the observeEvent
Changed the validate and need.
I want to create a reactive data frame with a reactive column name in shiny. However this is throwing error. I have provided the code below.. The error is being caused by an () followed by =, but I cant find a way around. Any help will be appreciated
ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("Tool"),
sidebarLayout(
sidebarPanel(
textInput("Item","Enter Item Name"),
div(class='row-fluid',
div(class='span6', numericInput("sales1","Enter Sales",value=0),numericInput("sales2","Enter Sales",value=0)),
div(class='span6', numericInput("prices1","Enter price",value=0),numericInput("prices2","Enter price",value=0))
)),
mainPanel(
dataTableOutput("table")
)
)
))
server.R
library(shiny)
shinyServer(function(input, output) {
prices<-reactive({
c(input$prices1,input$prices2)
})
sales<-reactive({
c(input$sales1,input$sales2)
})
combined<-reactive({
data.frame(prices(),sales())
})
combined_final<-reactive({
mutate(combined(),Rev=prices()*sales())
})
namerev<-reactive({
as.character(paste("Rev",input$Item,sep="_"))
})
combined_final_rename<-reactive({
rename_(combined_final(),namerev() ="Rev")
})
output$table<-renderDataTable({
combined_final_rename()
})
})
If I understood the question correctly, you might need something like that:
combined_final_rename<-reactive({
d <- combined_final()
colnames(d)[colnames(d)=='Rev'] <- namerev()
d
})
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
}
)