Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Subset dataset based on date inputs which should include NAs as choices

I have the shiny app below in which the dataset that is subseted by min and max date. In my dates I have NAs values which I want to include as choices in my selectInput(). But then I cannot make the subset work.

basically there should be 4 cases. one that no NA is selected,one that both are NA,one that only min is NA and one that only max is NA

library(shiny)
library(DT)

# Creating a sample dataframe
dates <- as.Date(c("2023-01-01", "2023-02-01", NA, "2023-04-01", "2023-05-01"))
names <- c("Alice", "Bob", "Charlie", "David", "Eve")

# Combine them into a dataframe
df <- data.frame(Date = dates, Name = names)

# Generate unique dates sorted in ascending order, including NA
unique_dates <- sort(unique(df$Date), na.last = TRUE)

# Creating a Shiny app
ui <- fluidPage(
  titlePanel("Subset Data by Date Range"),
  sidebarLayout(
    sidebarPanel(
      selectInput("start_date", "Start Date", choices = unique_dates, selected = unique_dates[1]),
      selectInput("end_date", "End Date", choices = unique_dates, selected = unique_dates[length(unique_dates)])
    ),
    mainPanel(
      dataTableOutput("table")
    )
  )
)

server <- function(input, output) {
  output$table <- renderDataTable({
    # Subset the dataframe based on the selected date range
    subset_df <- subset(df, Date >= input$start_date & Date <= input$end_date)
    datatable(subset_df)
  })
}

shinyApp(ui = ui, server = server)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do:

  output$table <- renderDataTable({
    # Subset the dataframe based on the selected date range
    if (input$start_date  == "NA" & input$end_date == "NA") {
      subset_df <- subset(df, is.na(Date))
    } else if (input$start_date == "NA") {
      subset_df <- subset(df, is.na(Date) | Date <= input$end_date)
    } else if (input$end_date == "NA") {
      subset_df <- subset(df, Date >= input$start_date | is.na(Date))
    } else {
      subset_df <- subset(df, Date >= input$start_date & Date <= input$end_date)
    }
    datatable(subset_df)
  })

Values in selectInput are strings.

Have a look at shiny::dateRangeInput, it might be more convenient to use.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading