简体   繁体   中英

How to order a factor variable within shinyapp

Within the shiny framework, I am trying to create an interactive table. As it is shown in this screenshot the age variable is not ordered. 屏幕截图 How can I fix this?

I tried the following code to order the age group variable but did not work.

 workforce_t <- workforce 

output$workforce_table_1 <- renderTable ({

  #sort the age_group variable
  workforce_t$Age_Group <- factor(
    workforce_t$Age_Group,
    levels = c(
      "16+",
      "16 to 24",
      "25 to 34",
      "35 to 44",
      "45 to 54",
      "55 to 64",
      "65+"
    ),
    labels = c(
      "16+",
      "16 to 24",
      "25 to 34",
      "35 to 44",
      "45 to 54",
      "55 to 64",
      "65+"
    )
  )

  info <- reactive ({
    out <- workforce_t %>%
      filter (County %in% input$county_workforce,
              #Year %in% input$years,
              Indicator %in% input$Indicator_workforce)
    return(out)

  })
  (info())
})

Thanks,

Nader

We can add an arrange statement for 'County', 'Age_Group'. As the 'Age_Group' is already a factor with levels specified, it would order based on the levels . Also, the assignment and return is optional. It can be made compact by removing those

info <- reactive({
   workforce_t %>%
      filter (County %in% input$county_workforce,
              #Year %in% input$years,
              Indicator %in% input$Indicator_workforce) %>%
      arrange(County, Age_Group)
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM