我试图从用户那里获取输入,并基于闪亮的应用程序中的线性回归来预测输出。请在以下Ui和服务器代码中找到:
ui.R
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("House median values"),
sidebarPanel(
numericInput(inputId = "incomeValue",
label = "incomeValue",
min = 40, max = 160, value = 100)
),
mainPanel()
))
server.R
library(shiny)
library(ISLR)
shinyServer(function(input, output) {
newlstat = renderText({input$incomeValue})
newPredict = data.frame(newlstat)
modelLM = lm(medv~lstat, data = Boston)
op = predict(modelLM, newPredict)
output$value <- renderPrint({op})
})
此代码导致预测函数出现以下错误:
Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) :
object is not a matrix
如何解决此错误并显示预测值?
答案 0 :(得分:0)
这是您的问题,因为renderText
返回的是函数而不是值
Browse[1]> str(newPredict)
'data.frame': 0 obs. of 1 variable:
$ lstat:function (...)
这是一个可行的示例
library(shiny)
ui <- fluidPage(
pageWithSidebar(
headerPanel("House median values"),
sidebarPanel(
numericInput(inputId = "incomeValue",
label = "incomeValue",
min = 40, max = 160, value = 100),
actionButton('go',"Predict")
),
mainPanel()
)
)
server <- function(input, output, session) {
data <- reactiveValues()
observeEvent(input$go,{
#browser()
data$var <-input$incomeValue
newPredict = data.frame(cyl=data$var)
modelLM = lm(hp~cyl, data = mtcars)
data$op = predict(modelLM, newPredict)
})
lstat = renderText({data$var})
output$value <- renderPrint({data$op})
}
shinyApp(ui, server)