Filtering date and data + OLS on Shiny

Hello my friends,

I m new as i'm happy to have discovered shiny. I look for help as since wednesday i try to learn how to filter date and date from a database as it looks less intuitive than in R. Please see a basic code (inspired from others people) from which i learn.

  1. code
    ==

set.seed(123)

foo <- data.frame(
date = sample(seq(as.Date('2010-01-01'), as.Date('2023-01-01'), by = 'day'), 20),
var1 = sample(1:15, 20, replace = TRUE),
var2 = sample(16:30, 20, replace = TRUE)
) %>%
arrange(date)

user interface

ui <- fluidPage(
sliderInput('year', 'Year', min = 2010, max = 2023,
step =1, value = c(2018,2020), sep = ''),

selectizeInput('data', 'Variable',
  choices = c("var1", "var2"), selected = "var1", multiple=FALSE),


dataTableOutput('table')
	    )

server <- function(input, output, session) {
dataset <- reactive({
foo %>%
filter(year(date) >= input$year[1], year(date) <= input$year[2])

			})
		

		output$table <- renderDataTable({
		dataset()
							 })
						}

Create Shiny app ----

shinyApp(ui, server)

==
2) 2 questions:

  • i would like the table to display the filtered dates with the chosen variable, let's say var1.
  • i would like to insert a plot/table to display e.g. the regression coefficients/R² of var2 on var1.

Many thanks for modifying the code to help me understand how manipulate Shiny.

Here is a very rough version of what I think you want.

library(shiny)
library(tidyverse)
#code
#==
  
  set.seed(123)

foo <- data.frame(
  date = sample(seq(as.Date('2010-01-01'), as.Date('2023-01-01'), by = 'day'), 20),
  var1 = sample(1:15, 20, replace = TRUE),
  var2 = sample(16:30, 20, replace = TRUE)
) %>%
  arrange(date)
#user interface

ui <- fluidPage(
  sliderInput('year', 'Year', min = 2010, max = 2023,
              step =1, value = c(2018,2020), sep = ''),
  
  selectizeInput('data', 'Variable',
                 choices = c("var1", "var2"), selected = "var1", multiple=FALSE),
  
  
  dataTableOutput('table'),
  
  textOutput("Corr"),
  plotOutput("Plot")
)

server <- function(input, output, session) {
  dataset <- reactive({
     foo %>%
      filter(year(date) >= input$year[1], year(date) <= input$year[2])
    
  })
  
  
  output$table <- renderDataTable({
    dataset()[, c("date", input$data)] #show only the selected column
  })
  output$Corr <- renderText({
    CORR <- round(cor(dataset()$var1, dataset()$var2), 3)
    paste("R squared =", CORR)
  })
  output$Plot <- renderPlot({
    plot(dataset()$var1, dataset()$var2)
  })
}

#Create Shiny app ----
  
  shinyApp(ui, server)

Hello

i would like to do prediction from a mutivariate ols lm (var3 ~ var 2 + var1) model by plugging numerical values from the fitted model (var1_hat, var2_hat) to get prediced forecast var3_hat. I did several tests but could not reach my goal.
Therefore could anyone could provide me with pedagogical simple reproducible code ? so many thanks and enjoy your last 2023 year my friends !!!

Here is an example of storing the fit coefficients and R^2 in a data frame and displaying that.

library(shiny)
library(tidyverse)
#code
#==
  
  set.seed(123)

foo <- data.frame(
  date = sample(seq(as.Date('2010-01-01'), as.Date('2023-01-01'), by = 'day'), 20),
  var1 = sample(1:15, 20, replace = TRUE),
  var2 = sample(16:30, 20, replace = TRUE)
) %>%
  arrange(date)
#user interface

ui <- fluidPage(
  sliderInput('year', 'Year', min = 2010, max = 2023,
              step =1, value = c(2018,2020), sep = ''),
  
  selectizeInput('data', 'Variable',
                 choices = c("var1", "var2"), selected = "var1", multiple=FALSE),
  
  
  dataTableOutput('table'),
  
  tableOutput("Corr"),
  plotOutput("Plot")
)

server <- function(input, output, session) {
  dataset <- reactive({
     foo %>%
      filter(year(date) >= input$year[1], year(date) <= input$year[2])
    
  })
  
  
  output$table <- renderDataTable({
    dataset()[, c("date", input$data)] #show only the select column
  })
  output$Corr <- renderTable({
   FIT <- lm(var2 ~ var1, data = dataset())
   Coef <- FIT$coefficients
    data.frame(Intercept = Coef[1], Slope = Coef[2], 
          R_squared = summary(FIT)$r.squared)
  })
  output$Plot <- renderPlot({
    plot(dataset()$var1, dataset()$var2)
  })
}

#Create Shiny app ----
  
  shinyApp(ui, server)

Thank you very much for your super proposal. I will test it tonight and come back tomorrow. I will also try to add new variables ilters with filter() and add a map. I love this new coding experience. Thanks again man !
Marco

Hello,

Please, i'm trying this time to apply additional variables v3/v4 filters to dates but got no good results and i'm disapointed by my skills given that i have two more hurdles (map with lat/longitude and compute f(xi) when users fullfil the xi s. Please, below is the code. Thank you very much.

====

set.seed(123)

foo <- data.frame(
date = sample(seq(as.Date('2010-01-01'), as.Date('2023-01-01'), by = 'day'), 20),
var1 = sample(1:15, 20, replace = TRUE),
var2 = sample(16:30, 20, replace = TRUE),
var3 = sample(0:1, 20, replace = TRUE),
var4 = sample(70:90, 20, replace = TRUE)

) %>%
arrange(date)

#user interface

ui <- fluidPage(

Sidebar layout with input and output definitions ----

sidebarLayout(

# Sidebar panel for inputs ----
	  sidebarPanel(

sliderInput('year', 'Year', min = 2010, max = 2023,
step =1, value = c(2018,2020), sep = ''),

selectInput('data', 'Variable',
choices = c("var1", "var2", "var3", "var4"), selected = "var1", multiple=TRUE),

selectizeInput('list1', 'List1', choices = unique(foo$var3), selected = "0", multiple=TRUE),

selectizeInput('list2', 'List2',choices = unique(foo$var4), selected = "72", multiple=TRUE),

numericInput("obs", "Number of observations to view:", 10)

			  ),

			

# Main panel for displaying outputs ----
	 mainPanel(

h4("Summary"),
  verbatimTextOutput("summary"),

h4("Observations"),
  tableOutput("view"),

dataTableOutput('table')
)
)
)

server <- function(input, output, session) {
dataset <- reactive({

foo %>%
filter(var3 == input$list1, var4 == input$list2,
year(date) >= input$year[1], year(date) <= input$year[2])

		   })



 output$summary <- renderPrint({
 dataset <- dataset()[, input$data]
 summary(dataset)
				   })



output$view <- renderTable({
	head(dataset(), n = isolate(input$obs))
head(dataset()[, c("date", input$data)], n = isolate(input$obs)) #show only the selected column
				  })

output$table <- renderDataTable({
dataset()[, c("date", input$data)] #show only the selected column
})

}

#Create Shiny app ----

shinyApp(ui, server)

Your code works to a certain extent but it probably needs some adjustment. The filtering is very strong, so you need to pick the inputs carefully. If I set the years to go from 2010 to 2020, List 1 = 1, List 2 = 72, and Number of Observations to 10, I see a summary and three rows of the data.

Picking more than one value for List 1 or List 2 won't work because you filter with filter(var3 == input$list1, var4 == input$list2. The == operator does not handle multiple values. You need to use %in%.

Thank you for your reponse.
I tried to mimic existing codes but it did not work indeed; it s like it filters too heavy.
Sure i tried : foo %in% input$list1 for ex but i could not find better.
I 'm a bit stressed by Shiny although it is a great tool, i have no intuition like on R for example.
In case you have a solution, it would be great of course.
Thanks a lot !

Hello,
I think i'm on the verge to solve the double filter issue.
I'm trying now a basic exercise to ask the user to insert X1, X2 et let the app returns Y (whatever is Y). Strangely i could not solve. Please any intuition? Many thanks !!!

===

user interface

ui <- fluidPage(

numericInput(inputId = "X1", label = "Select a number", min = 0, max = 10,
value = 0, step = 1),

numericInput(inputId = "X2", label = "Select a number", min = -10, max = 0,
value = 0, step = 1),

dataTableOutput('table')
	    )

server <- function(input, output, session) {

function_Y <- reactive({
			exp(input$X1) * exp(-input$X2+1)
			    })



		output$table <- renderDataTable({
		function_Y()
							 })
						}

Create Shiny app ----

shinyApp(ui, server)

===

Your function_Y returns a number yet you use it inside of renderDataTable(). You should use a data frame inside of renderDataTable(). Here are two versions of your code that do produce output. In the first I make a data frame to hold the result of function_Y(). In the second, I convert the result of function_Y() to characters and show it as text.

library(shiny)
#library(tidyverse)
ui <- fluidPage(
  
  numericInput(inputId = "X1", label = "Select a number", min = 0, max = 10,
               value = 0, step = 1),
  
  numericInput(inputId = "X2", label = "Select a number2", min = -10, max = 0,
               value = 0, step = 1),
  
  dataTableOutput("table")
)

server <- function(input, output, session) {
  
  function_Y <- reactive({
    exp(input$X1) * exp(-input$X2+1)
  })
  
  
  
  output$table <- renderDataTable({ 
    data.frame(Value = function_Y(), nrow = 1)
  })
}

#Create Shiny app ----
  
  shinyApp(ui, server)
library(shiny)
#library(tidyverse)
ui <- fluidPage(
  
  numericInput(inputId = "X1", label = "Select a number", min = 0, max = 10,
               value = 0, step = 1),
  
  numericInput(inputId = "X2", label = "Select a number2", min = -10, max = 0,
               value = 0, step = 1),
  
  textOutput("table")
)

server <- function(input, output, session) {
  
  function_Y <- reactive({
    exp(input$X1) * exp(-input$X2+1)
  })
  
  
  
  output$table <- renderText({ #
    as.character(function_Y())
  })
}

#Create Shiny app ----
  
  shinyApp(ui, server)

Hello,
Thank you very much, very nice approach to solve the issue, I did not understand why it asked me data.frame while i was expecting the user to insert figures...
i will run it tonight and come tomorrow.
Again, a great thanks !
Best,
Marco

Hello !
I m trying to locate points (name, date, longitude, latitude) on a map. I think i m close but no results. I would like ideally to use google map but it seems that it requires API (i have no such a thing). Any help would be greatly appreciated ! many thanks !!

===
library("maps")
#load("map")
mappy = data.frame(name = c("geo-1", "geo-2", "geo-3", "geo-4", "geo-5", "geo-6"),
date = c("2018-08-01","2019-03-01","2020-01-01","2021-12-01","2022-06-01","2023-09-01"),
latitude = c(-38.37602, -40.31389, -52.7558, 48.7550, 52.5486, 48.74404),
longitude = c(152.0765, 82.1185, 58.1474, 5.7318, 3.5684, 2.753459)
)

ui <- fluidPage(

sidebarLayout(
sidebarPanel(

sliderInput('year', 'Year', min = min(mappy$date), max = max(mappy$date),step =1, value=c(min(mappy$date), max(mappy$date)), sep = '')
),

mainPanel(plotOutput("map"))
	   
	  )
		)

server <- function(input, output) {

output$map <- renderPlot({
mappy %>%
filter(date == input$year) %>%
ggplot(data = mappy) +
borders("world", colour = "gray90", fill = "gray85") +
theme_map() +
geom_point(aes(x = longitude, y = latitude, size = 5),
colour = "#351C4D", alpha = 0.55) +
labs(size = "Users") +
ggtitle("Locations")

			})
					}

Create Shiny app ----

shinyApp(ui, server)

===

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.