Home > front end >  Create an else if statement that automatically accounts for new entries
Create an else if statement that automatically accounts for new entries

Time:11-29

I have created a shiny app that among other things shows the data of different years on a map. There is the possibility to select the year of interest. To do this I used the following code:

server <- function(input, output, session) {
  datasetInput <- reactive({
    if (input$myear_selected == 2017){
      MY17}
    else if (input$myear_selected == 2018){
      MY18}
    else if (input$myear_selected == 2019){
      MY19}
    else if (input$myear_selected == 2020){
      MY20}
    else if (input$myear_selected == 2021){
      MY21}
    else if (input$myear_selected == 2022){
      MY22}
    })

However, it is likely that data frames for future years will be added later. I would therefore like these years to be automatically taken into account. So far, I tried to create a data frame that includes just the right years and create a loop after. It looks like that, yet it does not work.

reac_matrix <- data.frame(matrix(ncol = 2,nrow = length(data_files)))

for (i in 1:length(data_files)) {
    reac_matrix[i,1] <- as.numeric(paste("20", i   16, sep = ""))
    reac_matrix[i,2] <- paste("MY", i   16, sep = "")
}

server <- function(input, output, session) {
  datasetInput <- reactive({
    for (i in 1:nrow(reac_matrix)) {
      if (input$myear_selected == reac_matrix[i,1]){
        get(reac_matrix[i,2])}
    }
  })

Thank you very much in advance for your precious help !!

CodePudding user response:

I would use a named list for this problem

dta_list <- #some code to generate a named list where each entry is named after the year it's representing

and the access it like this ihn the server code

server <- function(input, output, session) {
  datasetInput <- reactive({
    dta_list[[input$myear_selected]]
  })

Hope this helps!!

  • Related