错误:使用不同类型指定的变量适合闪亮

时间:2016-03-21 05:45:32

标签: shiny-server shiny

我正在尝试创建一个闪亮的应用程序,它使用分类算法来预测响应变量。在R上运行时,模型或predict函数没有问题。但是,在闪亮的情况下,它会出现以下错误:

Error: variables ‘X1’, ‘X2’, ‘X3’ were specified with different types from the fit.

以下是我为简化问题而创建的数据:

data1 <- data.frame(replicate(1,sample(c("a","b"), 1000, rep = TRUE)),
                replicate(3, sample(0:1, 1000, rep = TRUE)))
colnames(data1)[1] <- "outcome"

其中变量“outcome”是响应变量,“X1”,“X2”和“X3”是预测变量。

我训练过的模型如下:

modelFit <- train(outcome ~ ., data  = data1, method  = "glm")

这是Server.R

library(shiny)
library(caret)
library(shinyapps)
shinyServer(function(input, output){
  modelFit <- readRDS("modelFit.Rds")    
  userdf <- data1[1,]
  values <- reactiveValues()
  values$df <- userdf
  newEntry <- observe({
    values$df$X1 <- input$X1
    values$df$X2 <- input$X2
    values$df$X3 <- input$X3})
  output$results <- renderPrint({
    ds1 <- values$df
    a <- predict(modelFit, newdata = data.frame(ds1))
    names(a) <- NULL
    cat(a)
  })
})

,UI.R是

library(shiny)
shinyUI(fluidPage(
  tags$head(
    tags$style(HTML("
                  @import url('//fonts.googleapis.com/css?family=Lobster|Cabin:400,700');
                  h1 {
                  font-family: 'Lobster', cursive;
                  font-weight: 500;
                  line-height: 1.1;
                  color: #48ca3b;
                  }
                  "))
    ),
# Application title
  titlePanel(" Predictor",
           windowTitle = "random Predictor"),
  h5("Just for Fun"),

  sidebarLayout(sidebarPanel(
    hr(),
    h5('Enter parameters for prediction:'),
    hr(),
    selectInput("X1", 
                 label = h6("Numer of Bronze Badges"), 
                 choices = unique(data1$X1)),
    selectInput("X2", 
                 label = h6("Numer of Silver Badges"), 
                 choices  = unique(data1$X2)),
    selectInput("X3", 
                label = h6("Numer of blue Badges"), 
                choices  = unique(data1$X3))

  ),  #ends sidebarPanel

  mainPanel(
    tabsetPanel(
      tabPanel("Results", h2("The output is"),
               h2(verbatimTextOutput("results")),
               h2(" answers to your question."),
               p(), "Note:" , p(), "Look for it"))
      )
  )
))

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您必须强制将input$X强制转换为整数。

如果您向cat(str(input$X1))添加output$results,您会立即看到它被解释为字符而不是整数。

只需添加为。整数,例如:values$df$X1 <- as.integer(input$X1)使预测函数按预期再次起作用。