R Shiny: source command prints TRUE on app - r

I am building a shiny application that should have different options for different user categories. Therefore, I have different subfiles where the inputs are definied and the dependent on the role the respective file is loaded via the source command.
It works, however, the source command always prints a TRUE on my shiny app. I can't get rid of it no matter what option of the source command I am trying.
Here a screenshot of the problem
And a minimal example: app.R
library(shiny)
library(ggplot2)
# Define UI for app that draws a histogram ----
ui <- fluidPage(
titlePanel("Hello Shiny!"),
sidebarLayout(
sidebarPanel(
source("sub.R", echo = FALSE, print.eval = FALSE),
),
mainPanel(
plotOutput(outputId = "distPlot")
)
)
)
server <- function(input, output) {
output$distPlot <- renderPlot({
x <- faithful$waiting
ggplot(tibble(x), aes(x=x)) + geom_histogram( binwidth = input$bins)
})
}
shinyApp(ui = ui, server = server)
And the sourced file sub.R:
sliderInput(inputId = "bins",
label = "Number of bins:",
min = 0.1,
max = 5,
value = 1)
Thanks for any help in advance

I found the fix here: add a [1] at the end of the source(.) command:
library(shiny)
library(ggplot2)
# Define UI for app that draws a histogram ----
ui <- fluidPage(
titlePanel("Hello Shiny!"),
sidebarLayout(
sidebarPanel(
source("~/stackoverflow/17150062/sub.R", echo = FALSE, print.eval = FALSE)[1]
),
mainPanel(
plotOutput(outputId = "distPlot")
)
)
)
server <- function(input, output) {
output$distPlot <- renderPlot({
x <- faithful$waiting
ggplot(tibble(x), aes(x=x)) + geom_histogram( binwidth = input$bins)
})
}
shinyApp(ui = ui, server = server)

Related

Scatter plots for different variables in a single shiny app

I use R shiny to create multiple tabs for the scatter plot of different variables in a single app. My code seems alright, but the error says I have not "defined my main panel."
Can someone please help where I have gone wrong, or if my whole approach is inaccurateenter code here, please let me know!
library(shiny)
library(tidyverse)
India <- read.csv("D:/R/Practice 3/Indiadata.csv")
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Deaths vs all variables "),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("Deaths", "All variables:",
choices = c("cases"="total_cases","vaccinations"="total_vaccinations",
"people vaccinated"="people_vaccinated","people fully vaccinated"="people_fully_vaccinated",
"total booster"="total_boosters","new vaccinations"="new_vaccinations", "median age"="median_age"))
)
),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel(plotOutput("plot1")),
tabPanel(plotOutput("plot2")),
tabPanel(plotOutput("plot3")),
tabPanel(plotOutput("plot4")),
tabPanel(plotOutput("plot5")),
tabPanel(plotOutput("plot6")),
tabPanel(plotOutput("plot7"))
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$plot1 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=total_cases))
})
output$plot2 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=total_vaccinations))
})
output$plot3 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=people_vaccinated))
})
output$plot4 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=people_fully_vaccinated))
})
output$plot5 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=total_boosters))
})
output$plot6 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=new_vaccinations))
})
output$plot7 <- renderPlot({
ggplot(India,aes(y=total_deaths,x=median_age))
})
}
# Run the application
shinyApp(ui = ui, server = server)
mainPanel is an argument of the sidebarLayout() function. So, you just need to move it up into the sidebarLayout() function:
ui <- fluidPage(
# Application title
titlePanel("Deaths vs all variables "),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("Deaths", "All variables:",
choices = c("cases"="total_cases","vaccinations"="total_vaccinations",
"people vaccinated"="people_vaccinated","people fully vaccinated"="people_fully_vaccinated",
"total booster"="total_boosters","new vaccinations"="new_vaccinations", "median age"="median_age"))
),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel(plotOutput("plot1")),
tabPanel(plotOutput("plot2")),
tabPanel(plotOutput("plot3")),
tabPanel(plotOutput("plot4")),
tabPanel(plotOutput("plot5")),
tabPanel(plotOutput("plot6")),
tabPanel(plotOutput("plot7"))
)
)
)
)

ggplot not showing - area is blank

I am relatively new to ggplot2 and I have created a plot based on a csv file.
The problem I am having is that the plot is blank:
Nothing shows expect the title and I am not sure why!
As you can see the data is fine within RStudio:
My csv file is in the same directory as my app.R file:
My working directory is the same folder:
So why is ggplot2 failing to pick up the data held within the csv file?
Here is my code:
library(shiny)
library(ggplot2)
ui <- (fluidPage(
titlePanel("Pig Breeding")
)
)
mainPanel(
plotOutput(outputId = "scatterplot")
)
server <- (function(input, output){
output$scatterplot <- renderPlot({
pig_plot <- ggplot(read.csv("pigs_data.csv"),
aes_string(x = "species", y = "sow_count") +
geom_point())
})
})
shinyApp(ui, server)
the below code works with a test data called iris. Your mistake lies in your
ui <- (fluidPage(
titlePanel("Pig Breeding")
)
)
mainPanel(
plotOutput(outputId = "scatterplot")
)
ui code. You have left your mainPanel out of the fluidpage parenthesis. Thus, it does not read the plotOutput.
Example
library(shiny)
# Define UI for application
ui <- fluidPage(
# Application title
titlePanel("Iris data"),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
# Define server logic
server <- function(input, output) {
output$distPlot <- renderPlot({
ggplot(iris, aes(x=Sepal.Width, y=Petal.Width)) + geom_point()
})
}
# Run the application
shinyApp(ui = ui, server = server)
The code below should work for your question.
library(shiny)
# Define UI for application
ui <- fluidPage(
# Application title
titlePanel("Pig Breeding"),
# Show a plot of the generated distribution
mainPanel(
plotOutput("scatterplot")
)
)
# Define server logic
server <- function(input, output) {
output$scatterplot <- renderPlot({
ggplot(read.csv("pigs_data.csv"),
aes(x = "species", y = "sow_count")) + geom_point()
})
}
# Run the application
shinyApp(ui = ui, server = server)

Embed reactively generated URL in shiny

I would like to show in my shiny app a link that directs to the URL generated based on user's input. I don't want to show the full text of the URL. I know the a(href="",label="") function can be used if I know the URL beforehand, but in this case the URL depends on the user's input. The following doesn't work:
ui <- fluidPage(
titlePanel("Show map of a given state"),
sidebarLayout(
sidebarPanel(
textInput("state", label = "State", value = "CA", placeholder = "California or CA"),
actionButton("showU","Show map")
),
mainPanel(
conditionalPanel(
condition = "input.showU > 0",
htmlOutput("url"),
a(href=htmlOutput("url"),"Show in Google Map",target="_blank")
)
)
)
)
server <- function(input, output){
observeEvent(input$showU,{
output$url <-renderUI({paste("https://www.google.com/maps/place/", input$state, sep="")})
})
}
shinyApp(ui,server)
I hope I can click on the "Show in Google Map" and be directed to the URL generated on the fly. Please help me, thank you.
You need to use renderUI together with uiOutput to update UI reactively:
library(shiny)
ui <- fluidPage(
titlePanel("Show map of a given state"),
sidebarLayout(
sidebarPanel(
textInput("state", label = "State", value = "CA", placeholder = "California or CA"),
actionButton("showU","Show map")
),
mainPanel(
conditionalPanel(
condition = "input.showU > 0",
uiOutput("url")
)
)
)
)
server <- function(input, output){
observeEvent(input$showU,{
output$url <-renderUI(a(href=paste0('https://www.google.com/maps/place/', input$state),"Show in Google Map",target="_blank"))
})
}
shinyApp(ui,server)
If this questions is actually about creating reactive URL links, then HubertL's answer is the way to go.
If you want to keep the map and search funciton all self-contained in the shiny, rather than having to open a new link to Google Maps, you can use my googleway package to achieve the same task
library(shiny)
library(googleway)
ui <- fluidPage(
titlePanel("Show map of a given state"),
sidebarLayout(
sidebarPanel(
),
mainPanel(
google_mapOutput(outputId = "myMap", height = "600px")
)
)
)
server <- function(input, output){
## you need a valid API key from Google Maps
## https://developers.google.com/maps/
map_key <- "your_map_api_key"
output$myMap <- renderGoogle_map({
google_map(key = map_key, search_box = T)
})
}
shinyApp(ui,server)
I used a HTML button for which the url could be generated recursively
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("HTML button"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot"),
HTML(paste0(htmlOutput('url_test')))
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
output$url_test = renderText({
paste('Go to Google')
})
cultivar_url = reactive({
print('https://www.google.com')
})
}
# Run the application
shinyApp(ui = ui, server = server)

Disasble shiny sliderInput using shinyjs

I am building multiple lm() models using dplyr. I want to allow a user to change the independent variable value in a Shiny app - via shiny::sliderInput(). But only do so where "goodness of fit" say R^2 is greater than a threshold - otherwise disable the slider. I have tried to use the shinyjs::disable() function. See below, but can't get it to work. Any ideas on what I am doing wrong ?
library(shiny)
library(shinyjs)
# Define UI for application that draws a histogram
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("test","Nice number",min = 1,max = 50,value = 30)
),
mainPanel(
textOutput("valueText")
)
)
))
# Define server to disable slider if value selected
server <- shinyServer(function(input, output) {
value <- reactive(input$test)
output$valueText <- renderText(paste(value()))
#How to diasble slider?
reactive(if(value()==35){
shinyjs::disable('test')
}
)
})
# Run the application
shinyApp(ui = ui, server = server)
You have to call useShinyjs() in ui.R.
This is the code:
library(shiny)
library(shinyjs)
# Define UI for application that draws a histogram
ui <- shinyUI(
tagList(
useShinyjs(),
fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("test","Nice number",min = 1,max = 50,value = 30)
),
mainPanel(
textOutput("valueText")
)
)
)
)
)
# Define server to disable slider if value selected
server <- shinyServer(function(input, output) {
value <- reactive(input$test)
output$valueText <- renderText(paste(value()))
#How to diasble slider?
observeEvent(value(), {
if(value()==35){
shinyjs::disable('test')
}
})
})
# Run the application
shinyApp(ui = ui, server = server)

Chart (rCharts) is not shown in the web page (Shiny)

I am trying to embed the interactive chart from rCharts package. To embed the chart I have used the example from here (Shiny app).
The example works well but my prototype works without the chart output (no errors have been reported). My script is as follows:
ui.r:
library(shiny)
require(rCharts)
shinyUI(fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
showOutput("myChart", "polycharts")
)
)
))
server.r:
library(shiny)
require(rCharts)
shinyServer(function(input, output) {
observeEvent(input$bins,{
df2 <<- data.frame(x=c(1:input$bins),y=c(1:input$bins))
})
output$myChart <- renderChart({
print(df2)
p1 <- rPlot(df2$x,df2$y, data = df2, color='green', type = 'point')
p1$addParams(dom = 'myChart')
return(p1)
})
})
I have reviewed your code and here are some pointers:
1) rPlot is taking data as x~y along with color argument
2) It is better if you use the eventReactive and assign it to df2() instead of observe and <<- global assignment operator
rm(list = ls())
library(shiny)
require(rCharts)
server <- function(input, output) {
df2 <- eventReactive(input$bins,{data.frame(x=c(1:input$bins),y=c(1:input$bins))})
output$myChart <- renderChart({
p1 <- rPlot(x~y, data = df2(), color='green', type = 'point', color = 'x')
p1$addParams(dom = 'myChart')
return(p1)
})
}
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(sidebarPanel(sliderInput("bins","Number of bins:", min = 1,max = 50,value = 30)),
# Show a plot of the generated distribution
mainPanel(showOutput("myChart", "polycharts"))
)
)
shinyApp(ui, server)

Resources