我正在尝试生成一个闪亮的应用程序,该应用程序允许用户选择一个因变量和自变量,然后显示带有结果的表。这就是我所拥有的:
rule <- c("bb_rule", "pp_rule", "cb_rule")
dependent <- c("inning_fr", "innings_se", "inning_rain")
ui <- navbarPage(theme = shinytheme("simplex"), "App",
tabPanel("Regression Results",
fluidPage(
h3("Have Rule Changes Transformed ODI Cricket?"),
tableOutput("regression"),
sidebarPanel(
selectInput("depInput", "Dependent Variable",
choices=dependent),
selectInput("ruleInput", "Rule",
choices=rule)
)
))
)
server <- function(input, output) {
load("./data/data.RData")
output$regression <-
renderTable({
data %>%
lm(input$depInput ~ input$ruleInput, data = .) %>%
tidy(conf.int=TRUE) %>%
select(Variable = term,
Estimate = estimate,
`Lower Bound` = conf.low,
`Upper Bound` = conf.high) %>%
gt() %>%
tab_header(title = "Effect of Hours on Reported Approval Rating",
subtitle = "Data from TWT Archive")})
})
}
shinyApp(ui = ui, server = server)
不幸的是,这不起作用,并且我收到一条错误消息,Error: contrasts can be applied only to factors with 2 or more levels
但是,如果我直接在服务器中输入变量名称,则一切正常。似乎无法使用回归模型中的输入似乎是一个问题。
@@ phil有关使此功能生效的评论是正确的。但是我觉得还需要更多上下文。
通常,我们使用不带引号的变量名运行lm
:
lm(formula= Sepal.Width ~ Sepal.Length, data = iris)
但是input$rule
和input$dep
的值为character
。因此,实际上,代码要求shiny
执行:
lm(formula= "Sepal.Width" ~ "Sepal.Length", data = iris)
将导致错误。要使用lm
中的闪亮输入,我们必须转换为符号(sym
),然后强制进行早期评估(!!
),如@phil所示。