我正在尝试构建一个闪亮的应用程序,该应用程序可以根据各种用户输入给出新的预测。 但是,即使输入值随着输入而更新,预测值也不会更新。我在弄清楚原因时遇到了麻烦。
该模型是随机森林回归模型,在该示例中,我使用了数字变量,但在我的情况下,输入是分类的(我认为此更改不会产生任何影响),这就是为什么侧边栏都是选择输入而不是选择数字
我用mtcars数据集做了一个可重现的例子
model <- ranger(mpg ~ disp + hp + wt, data = mtcars)
ui <- fluidPage(
sidebarPanel(
selectInput('disp', 'disp',
choices = unique(mtcars$disp),
selected = unique(mtcars$disp)[1]),
selectInput('hp', 'hp',
choices = unique(mtcars$hp),
selected = unique(mtcars$hp)[1]),
selectInput('wt', 'wt',
choices = unique(mtcars$wt)),
actionButton("Enter", "Enter Values"),
width = 2
),
mainPanel(
tableOutput('mpg')
)
)
server <- function(input, output, session) {
val <- reactive({
new <- mtcars[1, ]
new$disp <- input$disp
new$hp <- input$hp
new$wt <- input$wt
new
})
out <- eventReactive(
input$Enter,
{
val <- val()
val$pred <- predict(model, data = val)$predictions
val
})
output$mpg <- renderTable({
out()
})
}
shinyApp(ui, server)
答案 0 :(得分:2)
这里有几个问题。
1)您使用的selectInput不正确。见下文。基本上,无论选择什么,使用mtcars $ disp [1]之类的索引都会创建静态值。
2)仅在生成单个值作为输出时,正在使用renderTable()。为什么不只使用renderText()?见下文。
3)需要使用eventReactive触发器(即input $ enter)来创建输入值的数据框。模型预测可以稍后在数据帧上运行,但是初始触发器实际上是从selectInput提取值的,因此触发器必须位于创建数据帧的同一块中。
此命令正确运行,并在我的计算机上产生了所需的输出:
library(shiny)
library(ranger)
model <- ranger(mpg ~ disp + hp + wt, data = mtcars)
ui <- fluidPage(
sidebarPanel(
selectInput('disp', 'disp',
unique(mtcars$disp)),
selectInput('hp', 'hp',
unique(mtcars$hp)),
selectInput('wt', 'wt',
unique(mtcars$wt)),
actionButton("enter", label = "Enter Values"),
width = 2
),
mainPanel(
textOutput('mpg')
)
)
server <- function(input, output, session) {
val <- eventReactive(
input$enter, {
data.frame(
disp = input$disp,
hp = input$hp,
wt = input$wt,
stringsAsFactors = F
)}
)
output$mpg <- renderText({
predict(model, val())[[1]]
})
}
shinyApp(ui, server)