来自调查包对象的反应数据的闪亮应用程序

时间:2018-03-17 19:18:36

标签: r shiny reactive-programming survey

我正在尝试构建一个简单的应用程序,以查看对教育部调查的回复。我正在使用survey package来调整复杂抽样设计的原始数据。这个包有几个内置函数,其中一个是svytable()。可以使用基函数svytable()直接绘制barplot()的输出。这很容易做到 - 但是,我无法让它在Shiny的反应式数据环境中工作。

(我希望能够使用ggplot2绘制此表中的数据,如果您将调查表对象强制转换为数据框,我可以将其开始迈出一步是时候看看我的应用程序出错了。)

如果您能确定我在这里遇到的问题,请告诉我们:

我已将数据样本上传到此link。以下是我的应用代码的简化示例,目前无效:

library(shiny)
library(foreign)
library(survey)

# Read in data (from wherever you save the data...)
secon_dat <- read.spss("FRSS_Short_Data.sav", 
                   use.value.labels = TRUE,
                   to.data.frame = TRUE)

# Define UI
ui <- fluidPage(

titlePanel("Secondary Arts Teacher Data 2009-2010"),

sidebarLayout(
  sidebarPanel(
    selectInput("xVar",
                 "Select Questionnaire Item",
                choices = c("School enrollment size" = "SIZE", "School 
                            community type" = "URBAN", 
                            "School region" = "OEREG", "School minority enrollment" = "MINST", 
                            "Percent of students in the school eligible for free or reduced-price lunch" = "POVST", 
                            "School level" = "LEVEL"),
                selected = "School community type"),
    selectInput("groupVar",
                "Select Grouping Item",
                choices = c("School enrollment size" = "SIZE", "School community type" = "URBAN", 
                            "School region" = "OEREG", "School minority enrollment" = "MINST", 
                            "Percent of students in the school eligible for free or reduced-price lunch" = "POVST", 
                            "School level" = "LEVEL"),
                selected = "School region")
  ),
  mainPanel(
     plotOutput("Plot")

  )))

server <- function(input, output) {

dat <- reactive({

 # Define complex survey design with replicate weights
      jrr_dat <- svrepdesign(variables = secon_dat[, c(which(colnames(secon_dat) == input$xVar),
                                                  which(colnames(secon_dat) == input$groupVar))],
                        repweights = secon_dat[, 9:58],
                        data = secon_dat,
                        type = "JK1",
                        combined.weights = TRUE,
                        weights = secon_dat[, 8],
                        scale = 1, rscales = 1)

 plot_tab <- svytable(~input$xVar + input$groupVar, jrr_dat)

 res <- list(plot_tab = plot_tab)

})

output$Plot <- renderPlot({

 res <- dat()

 barplot(res$plot_tab)

 })

}


shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:2)

您需要为svytable创建模型公式,如下所示:

model.formula <- formula(paste0("~",input$xVar," + ",input$groupVar))
plot_tab <- svytable(model.formula, jrr_dat)

enter image description here