[英]R shiny app error message from formula argument to `lm`
我正在嘗試使用多元線性回歸構建一個閃亮的應用程序,該應用程序允許選擇多個自變量,但目前停留在服務器端(我猜)。 來自此處的數據(表 1_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 變量,則反應循環會成功將其添加到公式中並計算結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.