从公式参数到 `lm` 的 R 闪亮应用程序错误消息

R shiny app error message from formula argument to `lm`

我正在尝试使用多元线性回归构建一个闪亮的应用程序,它允许选择多个独立变量但目前卡在服务器端(我猜)。数据来自 here (table1_1).

数据:

# A tibble: 1,289 x 6
    wage female nonwhite union education exper
   <dbl>  <dbl>    <dbl> <dbl>     <dbl> <dbl>
 1 11.55      1        0     0        12    20
 2  5.00      0        0     0         9     9
 3 12.00      0        0     0        16    15
 4  7.00      0        1     1        14    38
 5 21.15      1        1     0        16    19
 6  6.92      1        0     0        12     4
 7 10.00      1        0     0        12    14
 8  8.00      1        1     0        12    32
 9 15.63      0        0     0        18     7
10 18.22      1        0     0        18     5
# ... with 1,279 more rows

代码:

library(shiny)
library(shinydashboard)

ui <- shinyUI(
  dashboardPage(
    dashboardHeader(),
    dashboardSidebar(
      selectInput(inputId = "y", label = "Dependent Variable:", choices = names(table1_1[,c(2:7)])),
      selectInput(inputId = "x", label = "Independent Variable(s):",
                                 choices = names(table1_1[,c(2:7)]), multiple = TRUE),
                     sidebarMenu(
                       menuItem(text = "Summary", tabName = "summary_lm")
                     )
    ),
    dashboardBody(
      tabItems(
        tabItem(verbatimTextOutput("summary"), tabName = "summary_lm")
      )
    )
  )
)

server <- shinyServer(function(input,output){
  output$summary <- renderPrint({
    model <- reactive({
      lm(table1_1[,names(table1_1) %in% input$y] ~ table1_1[,names(table1_1) %in% input$x])
    })
    summary(model())
  })
})

shinyApp(ui,server)

错误:变量 'table1_1[, names(table1_1) %in% input$y]'

的无效类型(列表)

谁能帮我解决我的代码哪里出错了?

关于代码的哪一部分有问题的线索是正确的,它在服务器端部分是正确的。显示的页面(一旦您修复了引用不存在的第 7 个名称的代码中的错误)并且还修复了调用 lm 的公式的错误构造然后显示而没有错误:

Call:
lm(formula = form, data = table1_1)

Residuals:
1 
1 

No Coefficients

Residual standard error: 1 on 1 degrees of freedom

因为客户端代码中没有任何内容需要在 x 端选择变量。因此,这是修复有关公式构造的第一个重大错误的方法:

    server <- shinyServer(function(input,output){
  output$summary <- renderPrint({
    model <- reactive({ form <- as.formula( paste( names(table1_1)[names(table1_1) %in% input$y], "~", paste(names(table1_1)[names(table1_1) %in% input$x], collapse="+")))
      print(form)
      lm(form, data=table1_1)
    })
    summary(model())
  })
})

shinyApp(ui,server)

公式对象需要在语法上正确构建,如果需要计算参数,它们通常需要通过 as.formula 进行 R 清理。公式对象实际上不应该从调用环境中查找值。

(在将公式构造的表达式粘贴在一起后,我认为定义一个包含 tibble 对象名称的变量是个好主意。)

它现在可以工作了,尽管第一次出现的页面没有提供有关该事实的信息。如果您单击一个 y 变量,反应循环就会成功地将它添加到公式中并计算结果。