Referencing a selected input into a dataset? - r

I am currently having issues with my R.Shiny app which I have designed. The UI has a drop down menu which selects a variable "returnvar", one of the columns in my dataframe source_file. However, upon running the code below I receive an error message stating:
Warning: Unknown or uninitialised column: 'returnvar'.
Warning: Error in : geom_line requires the following missing aesthetics: y
Does anyone know how I can reference an input into my source file? (Something to fix the error from the line source_file_filtered$returnvar) Would greatly appreciate all the help I can get for this, thanks!
App.R
# Defining UI
ui <- fluidPage(theme = shinytheme("darkly"),
navbarPage(
"App", #Title of app
tabPanel("Weekly Cumulative Returns",
sidebarPanel(
tags$h3("Input:"),
dateRangeInput("daterange", "Date range",
start = "2016-01-01",
end = "2021-04-02",
min = "2016-01-01",
max = "2021-04-02",
format = "yyyy/mm/dd",
separator = "to"),
selectInput("returnvar", "Index",
choices= names(source_file[2:(length(source_file)-1)])),
), #sidebarpanel
mainPanel(
# Output: Correlation Plot ----
plotOutput(outputId = "plot2"),
), #mainPanel
) #tabpanel
) #navbarPage
) #fluidPage
# Defining Server
server <- function(input, output) {
#plot for Weekly Cumulative Returns tab
output$plot2 <- renderPlot({
returncolumn(returnvar = input$returnvar,
daterange = input$daterange)
})
}
# Create Shiny Object
shinyApp(ui = ui, server = server)
Global.R
#choose source file to work with
file_name = file.choose()
source_file = read_csv(file_name)
source_file$Date = as.Date(source_file$Date)
#defining returncolumn as a function to return of selected variable over the selected date range in shiny
returncolumn = function(returnvar, daterange)
{
source_file_filtered <- source_file %>%
filter(Date >= daterange[1] & Date <= daterange[2])
g = ggplot(data = source_file_filtered, mapping = aes(x=Date, y=source_file_filtered$returnvar)) + geom_line(color="blue")
print(g)
}

Without the data its hard to test, but changing source_file_filtered$returnvar to source_file_filtered[[returnvar]] should make it work.
returncolumn = function(returnvar, daterange)
{
source_file_filtered <- source_file %>%
filter(Date >= daterange[1] & Date <= daterange[2])
g = ggplot(data = source_file_filtered,
mapping = aes(x = Date,
y = source_file_filtered[[returnvar]])) +
geom_line(color="blue")
print(g)
}

Related

Using Shiny dateRangeInput to select only years

I am trying to implement something like the following post:
How to set daterangepicker to ONLY YEARS
I would like my dataRangeInput() to only accept values of years.
Currently the dataRangeInput() displays years but then goes on to ask for the month and day. I would like to avoid this since I am using yearly data and not daily/monthly.
Code:
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
dateRangeInput(
inputId = "myInputID",
label = h4("Year"),
start = as.Date("1990-01-04"),
end = as.Date("2005-10-23"),
# min = as.Date("1990-01-04"),
# max = as.Date("2022-10-23"),
startview = "year",
language = "es",
format = "yyyy",
separator = " - "
#startview = "decade"
),
actionButton(inputId = "apply_analysis", label = "Aplicar", icon = icon("play")),
plotOutput("out")
)
# Define server logic required to draw a histogram
server <- function(input, output) {
out = eventReactive(input$apply_analysis, {
managers %>%
data.frame() %>%
rownames_to_column("Date") %>%
mutate(year = lubridate::year(Date)) %>%
filter(year > input$myInputID)
})
output$myPlot = renderPlot({
out() %>%
ggplot(aes(x = year, y = HAM1)) +
geom_line() +
theme_bw()
})
}
# Run the application
shinyApp(ui = ui, server = server)

ggplot dateRangeInput in Rshiny

I am trying to make my line graph change based on the users input in the dateRangeInput widget in Rshiny. I have a column named SampleTime that has dates but every time I run the app I cannot seem to get the plot to change. I am obviously not linking this together correctly. Can anyone provide any input to this problem? Below is my code in app code in R.
library(tidyverse)
library(shiny)
# Define UI
ui <- fluidPage(
# Application title
titlePanel("TPO Data Over Time by Valve ID and Product Type"),
# Sidebar
sidebarLayout(
position = "left",
sidebarPanel(
selectInput(inputId = "valves",
label = strong("Valve ID"),
choices = unique(cTPO$ValveID),
selected = "1"),
selectInput(inputId = "products",
label = strong("Product Type"),
choices = unique(cTPO$Product),
selected = "12OZ CAN"),
dateRangeInput(inputId = "calendar",
label = 'Date range input: mm-dd-yyyy',
format = "mm-dd-yyyy",
start = NULL, end = NULL)),
mainPanel(
plotOutput("TPOPlot"))))
# Define server logic required to draw a line plot
server <- function(input, output) {
output$TPOPlot <- renderPlot({
## Read cTPO.csv and assign
cTPO <- read_csv("cTPO.csv")
## Get date from data
cTPO$SampleTime <- as.Date(cTPO$SampleTime, "%m/%d/%Y")
## Create point plot of TPO by valve number and product type
cTPO %>%
select(
ValveID,
BrandName,
Product,
TPOvalue,
CO2value,
LogIDKey,
SampleTime) %>%
filter_all(all_vars(!is.na(.)))
## Create line plot of TPO data
cTPO %>%
filter (ValveID == input$valves, Product == input$products) %>%
ggplot(aes (x = SampleTime, y = TPOvalue)) +
geom_line() +
labs (x = "Sample Date", y ="TPO Value") +
theme_bw()
})
}

Plotly event_register in Shiny app misfiring at the wrong moment

I'm struggling with a plotly event listener that seems to be active after its intended moment. I have two methods for selecting date range - a sliderInput and the plotlyOutput plot. While the Shiny reactivity and plotly event_register are generally responding as intended, the plotly event_register is also firing at an undesirable moment - when the user makes a selectInput choice after having clicked the button to reset following an earlier plotlyOutput drag-range selection.
The app below reproduces the problem. Assistance much appreciated.
require(tidyverse)
require(shiny)
require(plotly)
d = as_tibble(EuStockMarkets) %>% mutate(date = Sys.Date() + (-1860:-1)) %>%
pivot_longer(-date, names_to = 'market')
ui = fluidPage(
sidebarPanel(width = 3,
h5('Persistent sparkline to show full date range'),
plotOutput("sparkline", height = '100px'),
sliderInput('date_range', 'Date range', min = min(d$date), max = max(d$date),
value = range(d$date), step = 1, timeFormat = '%d %b %y'),
actionButton('reset_date_range', 'Reset sliderInput to full range', style='height: 25px; padding: 2px 5px;'),
hr(),
selectInput('market', 'Market', choices = unique(d$market), selected = 'DAX'),
h4('Steps to reproduce the problem:'),
p('1. Drag a date range in the big (plotly) plot. This will apply to sliderInput and main plot will update as intended.'),
p('2. Click the button to reset the range.'),
p('3. Select a new market. The sliderInput will revert to the last plotly plot\'s drag range despite the reset.'),
h5('Plotly event_register response:'),
verbatimTextOutput("brushed")
),
mainPanel(width = 9, plotlyOutput('plot', height='80vh'))
)
server = function(input, output, session) {
r = reactiveValues() # my app requires a reactive data object
observeEvent(input$market, {
r$dat = d %>% filter(market == local(input$market)) # filter reactive data
# Sparkline plot
output$sparkline = renderPlot({
d %>% filter(market == input$market) %>%
qplot(date, value, label = round(value), geom = 'line', data = .) +
geom_text(data = function(x){ filter(x, value %in% range(value))}, size = 4) +
theme_void() + scale_y_continuous(expand = c(0.2, 0.2))
}, bg="transparent")
# Plotly timeline plot
output$plot = renderPlotly({
p = r$dat %>% qplot(date, value, data = ., geom = 'line') + theme_minimal()
ggplotly(p) %>% layout(dragmode = "select") %>% event_register("plotly_brushed")
})
output$brushed <- renderPrint({
e_dat = event_data("plotly_brushed")
if(length(na.omit(e_dat$x)) == 2){
sliderRange <<- as.Date(e_dat$x, origin='1970-01-01')
updateSliderInput(session, 'date_range', value = sliderRange)
sliderRange <<- NULL # test to ensure e_dat$x isn't persisting somehow
}
print(e_dat)
})
})
# update reactive r$dat if the slider used
observeEvent(input$date_range, {
r$dat = d %>% filter(market == local(input$market), date >= input$date_range[1], date <= input$date_range[2])
})
# reset date selection
observeEvent(input$reset_date_range, {
date_range = range(d$date, na.rm = TRUE)
updateSliderInput(session, 'date_range', min = date_range[1], max = date_range[2], value = date_range)
})
}
shinyApp( ui = ui, server = server)
Agh rookie error.. my output$brushed <- renderPrint({ ... }) just needs to move outside the observeEvent(input$market, ...) clause.

R Shiny ggplot reactive to dateRangeInput

I am relatively new to R, and I'm trying to build a reactive ggplot in Shiny where the X-axis (dates) is reactive to a dateRangeInput in the UI. I've been googling everywhere, but every thing I try returns an error.
In the ggplot, the aes() calls from a dataset called datecorrected_totals, where x is the dates, and y=load are the two values that I would like to be reactive to the dateRangeInput so the ggplot will adjust the scale based on the period within the daterangeinput.
library(tidyverse)
library(shiny)
library(tidyr)
library(lubridate)
library(zoo)
data <- read_csv("--")
# Define UI ----
ui <- fluidPage(
titlePanel("--"),
sidebarLayout(
sidebarPanel(
h3("Calculator"),
dateRangeInput("dates", label = "Dates",
start = ("10-18-2018"),
end = max("05-29-2019"),
min = min("10-18-2018"),
max = max("05-29-2019"),
format = "mm-dd-yyyy"),
sliderInput("slider_a", label = "--",
min = 0,
max = 7,
value = 0),
sliderInput("slider_c", label = "--",
min = 7,
max = 42,
value = 7)
),
mainPanel(plotOutput('bar_chart'))
)
)
# Define server logic ----
server <- function(input, output, session) {
RE <- reactive({
})
output$bar_chart <- renderPlot(
ggplot(data = datecorrected_totals, aes(x = x, y = load)) +
geom_bar(stat = "identity")
)
}
# Run the app ----
shinyApp(ui = ui, server = server)
You need to filter the original dataset by the input dates. In this example data would be your original dataset.
RE <- reactive({
data %>%
filter(x>=input$dates[1] & x<=input$dates[2])
})
output$bar_chart <- renderPlot(
ggplot(data = RE(), aes(x = x, y = load)) +
geom_bar(stat = "identity")
There is no need to create a separate reactive() expression (unless required otherwise). The filter can be applied directly in renderPlot(). Thus, output$bar_chart becomes
output$bar_chart <- renderPlot(
datecorrected_totals %>%
filter(between(x, input$dates[1], input$dates[2])) %>%
ggplot(aes(x = x, y = load)) +
geom_bar(stat = "identity")
)
Below is a self-contained minimal reproducible example:
library(tidyverse)
library(lubridate)
library(shiny)
datecorrected_totals <- tibble(x = seq(as.Date("2018-10-18"), as.Date("2019-05-29"), length.out = 10L),
load = day(x))
# Define UI ----
ui <- fluidPage(
titlePanel("--"),
sidebarLayout(
sidebarPanel(
h3("Calculator"),
dateRangeInput("dates", label = "Dates",
start = mdy("10-18-2018"),
end = mdy("05-29-2019"),
min = mdy("10-18-2018"),
max = mdy("05-29-2019"),
format = "mm-dd-yyyy"),
),
mainPanel(plotOutput('bar_chart'))
)
)
# Define server logic ----
server <- function(input, output, session) {
output$bar_chart <- renderPlot(
datecorrected_totals %>%
filter(between(x, input$dates[1], input$dates[2])) %>%
ggplot(aes(x = x, y = load)) +
geom_col()
)
}
# Run the app ----
shinyApp(ui = ui, server = server)
Note that the date strings have been coerced to valid Date objects by calling mdy() to avoid error messages.
In addition, geom_bar(stat = "identity") has been replaced by geom_col().

Why is plot not displayed in the main panel?

I'm new to R shiny and trying to generate plots in the dashboard. Everything gets displayed but the plots. I do not get errors too. Could anyone say, what exactly I'm doing wrong?
I tried using different options for generating graphs like
ggplot, plotOutput. Neither works.
library(shiny)
library(lubridate)
library(ggplot2)
library(scales)
library(dplyr)
library(shinydashboard)
data <- read.csv("sample.csv", stringsAsFactors = F, header = T)
ui <- fluidPage(
dateRangeInput("daterange", "Choose the date",
start = min(data$YEAR),
end = max(data$YEAR),
min = min(data$YEAR),
max = max(data$YEAR),
separator = " - ", format = "dd/mm/yy",
startview = 'Week', language = 'Eng', weekstart = 1),
selectInput(inputId = 'Product',
label='Product',
choices=c('Product1','Product2'),
selected='Product1'),
plotOutput("barplot", height = 500))
server <- function(input, output) {
a<-reactive({
data <- read.csv("sample.csv", stringsAsFactors = F, header = T)
dataset <- subset(data, Date >= input$daterange[1] & Date <= input$daterange[2])
dataset = switch(input$Product,
"Product1" = Product1,
"Product2" = Product2)
dataset
})
output$barplot <-renderPlot({
color<- c("blue", "green")
barplot(data$PRODUCT, data$VALUE,
col = color)
})
}
shinyApp (ui = ui, server = server)
I get no errors.

Resources