使用reactiveValues()在Shiny中绘制动态C5.0决策树

时间:2016-09-22 08:23:53

标签: r shiny

我正在开发一个Shiny应用程序,让用户按需选择依赖/自变量,然后执行C5.0生成摘要和树形图。但是,生成有关plot方法的绘图时无法找到相应的对象时出现错误消息。这是Plotting a dynamic C5.0 decision tree in Shiny的扩展问题。在将plot转换为iris对象而非简单数据框后,reactiveValue()方法再次失败,请找到代码:

# ui.R
library(shiny)

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)

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)
  })
  # tranforming iris to reactiveValues() object
  react_vals <- reactiveValues(data = NULL)
  react_vals$data <- iris

  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 = %s)", form, 'react_vals$data')))
    output$tree_summary <- renderPrint(summary(c50_fit))
    output$tree_plot_c50 <- renderPlot({
      plot(c50_fit)
    })
  })
}

1 个答案:

答案 0 :(得分:1)

我的猜测plot方法在全局环境中寻找react_vals;如果是这样的话,一个简单的解决方案(但不是理想的)就是使用iris<<-分配给全局环境中的变量。在server.R

# tranforming iris to reactiveValues() object
react_vals <<- reactiveValues(data = NULL)
react_vals$data <<- iris

一个简单的实验证实了我的猜测;在函数中包装C5.0()然后plot()会引发错误:

library(C50)
test <- function(dat) {
  fit <- C5.0(Species ~ Sepal.Length, dat)
  plot(fit)
}

test(iris)
# Error in is.data.frame(data) : object 'dat' not found