由于数据中存在NA,因此无法在R Shiny中绘制直方图

时间:2018-04-13 14:02:29

标签: r shiny histogram

我正在创建一个Shiny应用程序,其中有一个下拉列表,它将值发送到服务器以创建直方图。

代码如下所示

用户界面:

 selectInput(inputId = "diamonds", 
              label = "choose a category in Diamonds", 
              choices = c("Length", "Breath", "Height"," Please Select a Type "),
              selected = " Please Select a Type " ),

服务器:

datasetInput <- reactive({ 
    switch(input$dataset, 
           "Length" = diamonds$x, 
           "Breath" = diamonds$y, 
           "Height" = diamonds$z,
           " Please Select a Type " = NULL) 
  }) 
  output$hist <- eventReactive(input$action,{hist(rnorm(input$diamonds))
  })

因此,当我从下拉列表中选择任何内容并单击“提交”按钮时,它会显示

Error Msg: Listening on http://127.0.0.1:6691 Warning in rnorm(input$diamonds) : NAs introduced by coercion Warning: Error in rnorm: invalid arguments Stack trace (innermost first):   
    100: rnorm
     99: hist
     98: eventReactiveHandler [#10]
     78: output$hist
      4: <Anonymous>
      3: do.call
      2: print.shiny.appobj
      1: <Promise>

创建直方图时如何避免NA?

2 个答案:

答案 0 :(得分:1)

您的问题与NA无关。阅读该错误消息的第二部分:Error in rnorm: invalid arguments Stack trace (innermost first)

问题是rnorm()接受一个数值参数,该参数确定从正态分布中产生多少随机数。您可以使用rnorm(input$diamonds)来调用它,其中input$diamonds会返回selectInput的所选值,所有值都是字符串:choices = c("Length", "Breath", "Height"," Please Select a Type ")

您的代码应为:

datasetInput <- reactive({ 
    switch(input$diamonds, 
           "Length" = diamonds$x, 
           "Breath" = diamonds$y, 
           "Height" = diamonds$z,
           " Please Select a Type " = NULL) 
  })
  output$hist <- eventReactive(input$action,{hist(rnorm(datasetInput()))
  })

您需要在datasetInput()来电中致电rnorm(),以便获得相应的数字值,而非input$diamonds,将选择作为字符返回

答案 1 :(得分:0)

是的,实际问题是rnorm()方法。在这里,如果我们使用rnorm(),则无论切换情况中的任何选择如何,它都会给出相同的结果。要获得精确的直方图,我们必须删除rnorm方法,然后调用datasetInput()方法。

datasetInput <- reactive({ 
    switch(input$diamonds1, 
           "Length" = diamonds$x, 
           "Breath" = diamonds$y, 
           "Height" = diamonds$z,
           " Please Select a Type " = NULL) 
  }) 
  output$hist <- eventReactive(input$action,{**hist(datasetInput())**

感谢您的帮助@divibisan,让我接近解决方案。