【问题标题】:Plotting a dynamic C5.0 decision tree in Shiny在 Shiny 中绘制动态 C5.0 决策树
【发布时间】:2017-07-21 03:09:18
【问题描述】:

我正在开发一个 Shiny 应用程序,让用户根据需要选择因/自变量,然后执行 C5.0 以生成摘要和树形图。但是,生成绘图时出现错误消息。有谁知道解决方案?请找到代码:

library(shiny)

ui <- fluidPage(
  titlePanel('Plotting Decision Tree'),
  sidebarLayout(
    sidebarPanel(
      h3('iris data'),
      uiOutput('choose_y'),
      uiOutput('choose_x'),
      actionButton('c50', label = 'Generate C5.0 summary and plot')
    ),
    mainPanel(
      verbatimTextOutput('tree_summary'),
      plotOutput('tree_plot_c50')
    )
  )
)

# server.R
library(shiny)
library(C50)

server <- function(input, output) {
  output$choose_y <- renderUI({
    is_factor <- sapply(iris, FUN = is.factor)
    y_choices <- names(iris)[is_factor]
    selectInput('choose_y', label = 'Choose Target Variable', choices = y_choices)
  })

  output$choose_x <- renderUI({
    x_choices <- names(iris)[!names(iris) %in% input$choose_y]
    checkboxGroupInput('choose_x', label = 'Choose Predictors', choices = x_choices)
  })

  observeEvent(input$c50, {
    c50_fit <- C5.0(as.formula(paste(isolate(input$choose_y), '~', paste(isolate(input$choose_x), collapse = '+'))), data = iris)
    output$tree_summary <- renderPrint(summary(c50_fit))
    output$tree_plot_c50 <- renderPlot({
      plot(c50_fit)
    })
  })
}

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    在你的server.R试试

    function(input, output) {
      output$choose_y <- renderUI({
        is_factor <- sapply(iris, FUN = is.factor)
        y_choices <- names(iris)[is_factor]
        selectInput('choose_y', label = 'Choose Target Variable', choices = y_choices)
      })
    
      output$choose_x <- renderUI({
        x_choices <- names(iris)[!names(iris) %in% input$choose_y]
        checkboxGroupInput('choose_x', label = 'Choose Predictors', choices = x_choices)
      })
    
      observeEvent(input$c50, {
        form <- paste(isolate(input$choose_y), '~', paste(isolate(input$choose_x), collapse = '+'))
        c50_fit <- eval(parse(text = sprintf("C5.0(%s, data = iris)", form)))
        output$tree_summary <- renderPrint(summary(c50_fit))
        output$tree_plot_c50 <- renderPlot({
          plot(c50_fit)
        })
      })
    }
    

    解释。plot 方法似乎正在寻找C5.0() 的返回值的call 元素中指定的术语,并在找不到它们时引发错误。在您的情况下,这指的是 input 对象。解决方法是调用C5.0(),并通过eval(parse(text = ...)) 构造完全指定公式(例如Species ~ Sepal.Length + Petal.Width)。

    【讨论】:

    • 很棒的解决方案,解释也是如此!非常感谢!
    • 附加问题:如果我的 iris 数据是 reactiveValues 对象怎么办?说:react_vals &lt;- reactiveValues(data = NULL)react_vals$data &lt;- iris,一旦我将iris 转换为 reactiveValues 对象,plot 方法就会失败。
    • 这似乎不是一个单一解决方案的问题,你应该用一个最小的例子打开一个新问题。
    • 没问题,我开个新问题!
    猜你喜欢
    • 2017-01-30
    • 2015-12-18
    • 2021-10-01
    • 2017-02-21
    • 2014-08-30
    • 2016-11-09
    • 1970-01-01
    • 2013-02-09
    • 2018-12-21
    相关资源
    最近更新 更多