【问题标题】:Shiny R Histogram闪亮的 R 直方图
【发布时间】:2019-03-07 19:03:39
【问题描述】:

我使用下面的代码来倾斜 Shiny R,当我运行这段代码时,它给了我这个错误:

警告:hist.default 中的错误:“x”必须是数字 [没有可用的堆栈跟踪]

library(shiny)

ui <- fluidPage(
  selectInput("Ind","Indipendent Variable",choices = names(mtcars)),
  selectInput('Dep','  Dependent Variable',choices = names(mtcars)),
  plotOutput("BoxPlot"),
  plotOutput('Hist'))

server <- function(input, output, session) {

  data1 <- reactive({input$Ind})
  data2 <- reactive({input$Dep})

  output$BoxPlot <- renderPlot({boxplot(get(data2()) ~ get(data1()) , data=mtcars)})

  output$Hist <- renderPlot({hist(get(data1())}) 

}

shinyApp(ui, server)

任何帮助为什么会这样说?

【问题讨论】:

    标签: r shiny histogram


    【解决方案1】:

    尽量不要将所有内容放在 1 行中,因为它不会提高可读性,如果您愿意,可以使用 Google's R Style Guide。要回答您的问题,您可以通过 [[]] 访问变量,如下所示:

    library(shiny)
    
    ui <- fluidPage(
      selectInput("Ind","Indipendent Variable",choices = names(mtcars)),
      selectInput('Dep','  Dependent Variable',choices = names(mtcars)),
      plotOutput("BoxPlot"),
      plotOutput('Hist')
    )
    server <- function(input, output, session) {
    
      data1 <- reactive({
        input$Ind
      })
      data2 <- reactive({
        input$Dep
      })
    
      output$BoxPlot <- renderPlot({
        boxplot(get(data2()) ~ get(data1()) , data=mtcars)
      })
    
      output$Hist <- renderPlot({
        req(data1())
        hist(mtcars[[data1()]])
      }) 
    
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    • 嗨猪排,很好的建议。它有效,但快速提问,[] 和 [[]] 之间有什么区别
    • 双括号用于访问更复杂对象(例如列表)中的变量,您可以在这个不错的博客davetang.org/muse/2013/08/16/double-square-brackets-in-r 和手册cran.r-project.org/doc/manuals/R-lang.html#Indexing 中阅读更多内容
    • 太棒了,为什么我们需要 req 函数?我还注意到我们将它用于直方图,但没有用于箱线图,为什么呢?非常感谢您的帮助
    • 使用req()只是我的一个习惯,我认为这是一个很好的习惯,除非你动态生成内容,否则你不应该在这里需要它
    • @Fahadakbar 可能还值得指出的是,它最初不起作用的原因是因为get(data1()) 被翻译成例如get("mpg"),它返回整个@987654331 @ 数据框。因此,您最初是在数据框上调用 hist,而不是在特定变量上调用。这个答案通过直接从mtcars 数据集调用变量来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多