【发布时间】:2019-06-30 23:22:12
【问题描述】:
我正在尝试构建一个闪亮的应用程序,它可以根据各种用户输入提供新的预测。 然而,即使输入值随着输入而更新,预测值也不会更新。我很难找出原因。
该模型是一个随机森林回归模型,在示例中我使用的是数字变量,但在我的情况下,输入是分类的(我认为这种更改不会影响任何东西)这就是为什么侧边栏都是选择输入而不是选择数字
我用 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)
【问题讨论】:
-
predict()的参数应该是newdata=,而不是data= -
将代码更改为
val$pred <- predict(model, newdata = val)$predictions会引发此错误:错误:非分位数预测需要参数“数据”。 -
在闪亮之外运行时,数据参数也可以正常工作
-
抱歉,我猜
ranger()必须使用与使用predict()的所有其他对象不同的约定。请务必明确列出您使用的任何非基础 R 包。放入所有library()命令,以便我们可以复制/粘贴代码进行测试。 -
是的,我应该使用
caret包包含该即时消息
标签: r shiny random-forest predict