fix selectInput error on initial shinyr app load - r

When the shiny app below is run I initially get the error - invalid type/length (symbol/0) in vector allocation. However, as soon as I click "Submit" the app functions as intended.
Is there a way to avoid this launch error and have it work correctly from the start?
plot_and_summary <- function(dat, col){
summary <- dat %>% summarize_(mean = interp(~mean(x), x = as.name(col)),
sd = interp(~sd(x), x = as.name(col)))
plot <- ggplot(dat, aes_string(x = col)) + geom_histogram()
return(list(summary = summary, plot = plot))
}
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
titlePanel(""),
sidebarLayout(
sidebarPanel(
uiOutput("column_select"),
submitButton("Submit")
),
mainPanel(
tableOutput("summary"),
plotOutput("plot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output){
dat <- reactive({iris})
output$column_select <- renderUI({selectInput("col", label = "select column", choices = as.list(names(dat())))})
pas <- reactive({plot_and_summary(dat(), input$col)})
output$plot <- renderPlot({pas()$plot})
output$summary <- renderTable({pas()$summary})
}
shinyApp(ui = ui, server = server)

The req function should solve your problem
http://shiny.rstudio.com/reference/shiny/latest/req.html
pas <- reactive({plot_and_summary(dat(), req(input$col))})

Related

How to use plotmeans or geom_errorbar for a Shiny app

Good day
I am trying to plot the means and 95% confidence intervals for my shiny webpage but I can't seem to get it right.
I would like output similar to this
I have tried two methods
Using geom_errorbar
Here I tried creating a summary table that calculates the 95% CI and then plotting from there.
My code follows
ui <- fluidPage(
titlePanel("questionnaire"),
sidebarLayout(
sidebarPanel(
selectInput("question", "Choose a question",
colnames(Data[,3:(ncol(Data)-1)]))
),
mainPanel(
plotOutput("meanCI")
)
)
)
server <- function(input, output) {
ci <- reactive({
groupwiseMean(input$question ~ Date,
data = Data,
conf = 0.95,
digits = 3)
})
output$meanCI <- renderPlot(
ggplot(ci, aes(x=Date, y=Mean)) +
geom_errorbar(aes(ymin=Trad.lower, ymax=Trad.upper), width=.1) +
geom_point()
)
}
shinyApp(ui = ui, server = server)
But it gives me this error,
data must be a data frame, or other object coercible by fortify(), not an S3 object with class reactiveExpr/reactive
Option 2 was to use plotmeans from the gplot package
ui <- fluidPage(
titlePanel("questionnaire"),
sidebarLayout(
sidebarPanel(
selectInput("question", "Choose a question",
colnames(Data[,3:(ncol(Data)-1)]))
),
mainPanel(
plotOutput("meanCI")
)
)
)
server <- function(input, output) {
output$meanCI <- renderPlot(
plotmeans(input$question~Data$Date, connect = FALSE)
)
}
shinyApp(ui = ui, server = server)
But it results is this error,
variable lengths differ (found for 'Data$Date')
Any help will be greatly appreciated!
library(shiny)
library(rcompanion)
library(ggplot2)
ui <- fluidPage(
titlePanel("questionnaire"),
sidebarLayout(
sidebarPanel(
selectInput("question", "Choose a question",
colnames(iris)[1:4])
),
mainPanel(
plotOutput("meanCI")
)
)
)
server <- function(input, output) {
ci <- reactive({
groupwiseMean(data = iris,
var = input[["question"]],
group = "Species",
conf = 0.95,
digits = 3)
})
output[["meanCI"]] <- renderPlot({
ggplot(ci(), aes(x=Species, y=Mean)) +
geom_errorbar(aes(ymin=Trad.lower, ymax=Trad.upper), width=.1) +
geom_point()
})
}
shinyApp(ui = ui, server = server)
Your main error is the missing parentheses in ggplot(ci(), ....... The other one is input$question ~ Date, which doesn't work because input$question is a character string.

Cannot coerce class ""histogram"" to a data.frame error in when plotting a graph in Shiny

I have the following data frame that I extract from google analytics
ga_data <- google_analytics_4(viewId = my_id,
date_range = c(Sys.Date()-7, Sys.Date()-1),
metrics = c("sessions","pageviews",
"entrances","bounces"),
dimensions = c("date","deviceCategory",
"channelGrouping"),
anti_sample = TRUE)
Now I want to show a graph of ga_data in a Shiny application. Therefore I include the following code:
library(shiny)
library(ggplot2)
ui <- fluidPage(
titlePanel("Shiny Text"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "dataset",
label = "Choose a dataset:",
choices = c("ga_data")),
numericInput(inputId = "obs",
label = "Number of observations to view:",
value = 10)
),
mainPanel(
verbatimTextOutput("summary"),
tableOutput("view")
)
)
)
server <- function(input, output) {
ga_data <- google_analytics_4(viewId = 156004565,
date_range = c(Sys.Date()-7, Sys.Date()-1),
metrics = c("sessions","pageviews",
"entrances","bounces"),
dimensions = c("date","deviceCategory",
"channelGrouping"),
anti_sample = TRUE)
datasetInput <- reactive({
switch(input$dataset,
"ga_data" = ga_data)
})
output$view <- renderTable({
hist(ga_data$sessions)
})
}
shinyApp(ui = ui, server = server)
However when I run it I get the following error:
cannot coerce class ""histogram"" to a data.frame
But this is strange cause when I want to make normal plot of the dataframe it does work. So the problem probably has to do with Shiny.
Any thoughts on what can go wrong here?
Since I don't have googleAnalyticsR set up, I reduced your problem to his simple app.
library(shiny)
shinyApp(
fluidPage(tableOutput("table")),
server = function(input, output, session){
output$table <- renderTable({hist(mtcars$mpg)})
}
)
## Warning: Error in as.data.frame.default: cannot coerce class ""histogram"" to a
## data.frame
The problem here is that you try to render a plot using renderTable. If you use renderPlot instead, everything works.
shinyApp(
fluidPage(plotOutput("plot")),
server = function(input, output, session){
output$plot <- renderPlot({hist(mtcars$mpg)})
}
)

shiny - interactive ggplot with subset

I am new to R&shiny. I'd like to make a shiny app that the plot can be interactive with subset I choose, but ggplot cannot work with warning
Error in ouptut$Trendplot <- renderPlot({ : object 'ouptut' not found
It will be really appreciated if you can help to figure it works.
The following is my code:
library(shiny)
library(ggplot2)
# Define UI for application that draws a histogram
ui <- pageWithSidebar(
# Application title
headerPanel("Pre-report situation"),
# Sidebar with a slider input for number of bins
sidebarPanel(selectizeInput("DMS", "DMS:", choices = unique(datass$DMS)
)),
# Show a plot of the generated distribution
mainPanel(
h3(textOutput("caption")),
plotOutput("Trendplot"))
)
datass <- read.csv("C:/Users/yyu6/Documents/PR.csv", sep=",", stringsAsFactors = FALSE)
# Define server logic required to draw a histogram
server <- function(input, output) {
formulaText <- reactive({
input$DMS })
datasetInput <- reactive({
selection <- Input$DMS
subset(datass, DMS == selection)
})
output$caption <- renderText({formulaText()
})
ouptut$Trendplot <- renderPlot({
ggplot(datasetInput(), mapping = aes(x=DMS))+geom_histogram(stat = "count")
})
}
# Run the application
shinyApp(ui = ui, server = server)

How can I unpick the renderPlot() function in shinyr with ggplot

Below is functioning code for a basic shiny app that allows the user to pick a column and then plots a ggplot::histogram() of the selected column:
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
titlePanel("ggplot"),
sidebarLayout(
sidebarPanel(
uiOutput("column_select")
),
mainPanel(plotOutput("plot"))
)
)
# Define server logic required to draw a histogram
server <- function(input, output){
dat <- reactive({iris})
output$column_select <- renderUI({selectInput("col", label = "column", choices = as.list(names(iris)), selected = "Sepal.Length")})
output$plot <- renderPlot({ggplot(dat(), aes_string(x = input$col)) +
geom_histogram()})
p <- ggplot(dat(), aes_string(x = input$col)) +
geom_histogram()
renderPlot
}
# Run the application
shinyApp(ui = ui, server = server)
I am not sure, however, why I am unable to remove the ggplot() function from within renderPlot() and still get the same result. I have tried:
p <- reactive({ggplot(dat(), aes_string(x = input$col)) +
geom_histogram()})
outputPlot <- renderPlot({p})
But this results in no plot being drawn.
I assume there is a simple fix to this, but thus far it escapes me.

Mouseover in plotly and shiny

I have some plotly code that perfectly calls the row names of a dataframe on mouseover both within RStudio and on RPubs . . . but not when embedded in Shiny.
The basic code is:
require(shiny)
require(plotly)
Trial <- read.table("http://history.emory.edu/RAVINA/Aozora/Data/Trial.txt", row.names = 1)
plot_ly(Trial, x=V1, y=V2, text=rownames(Trial), mode = "markers")
The Shiny version, however, is completely dead. What am I missing?
require(shiny)
require(plotly)
Trial <- read.table("http://history.emory.edu/RAVINA/Aozora/Data/Trial.txt", row.names = 1)
ui <- fluidPage(
titlePanel("Word Frequency Analysis for Meiji-era Authors"),
mainPanel(
plotOutput("plot"),
dataTableOutput("Print")
)
)
server <- function(input, output){
output$plot<-renderPlot({
p <- plot_ly(Trial, x=V1, y=V2, text=rownames(Trial), mode = "text")
plot(p)
})
output$Print<-renderDataTable({Trial})
}
shinyApp(ui = ui, server = server)
You need to swap out some base shiny functions for their plotly counterparts. Namely plotOutput -> plotlyOutput and renderPlot -> renderPlotly. Also, that last plot(p) isn't what you want to return: you just want to return p (the plot object).
require(shiny)
require(plotly)
Trial <- read.table("http://history.emory.edu/RAVINA/Aozora/Data/Trial.txt", row.names = 1)
ui <- fluidPage(
titlePanel("Word Frequency Analysis for Meiji-era Authors"),
mainPanel(
plotlyOutput("plot"),
dataTableOutput("Print")
)
)
server <- function(input, output){
output$plot<-renderPlotly({
p <- plot_ly(Trial, x=V1, y=V2, text=rownames(Trial), mode = "text")
#plot(p)
p
})
output$Print<-renderDataTable({Trial})
}
shinyApp(ui = ui, server = server)

Resources