首页 > 解决方案 > 如何在 shinyapp 中订购因子变量

问题描述

在闪亮的框架内,我正在尝试创建一个交互式表格。如此屏幕截图所示,年龄变量未排序。截屏我怎样才能解决这个问题?

我尝试了以下代码来订购年龄组变量,但没有奏效。

 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())
})

谢谢,

纳德

标签: rshinydplyr

解决方案


我们可以arrange为“County”、“Age_Group”添加一个语句。由于 'Age_Group' 已经是一个factorwithlevels指定的,它会根据levels. 此外,分配和return是可选的。它可以通过删除那些变得紧凑

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

推荐阅读