【问题标题】:Box Plot in Shiny RShiny R中的箱线图
【发布时间】:2018-10-01 15:09:01
【问题描述】:

我正在尝试通过 Shiny 创建/学习交互式箱线图,下面是我尝试使用的代码。这给了我错误

警告:model.frame.default 中的错误:可变长度不同(为 'input$p' 找到)
[没有可用的堆栈跟踪]

我无法弄清楚,任何帮助将不胜感激

代码:

library(shiny)

ui <- fluidPage(
  selectInput("p","p",choices = names(mtcars)),
  plotOutput("myplot"))

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

  output$myplot <- renderPlot({
    boxplot(mpg ~ input$p , data=mtcars)
  })
}

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny boxplot


    【解决方案1】:

    你为什么不直接使用get

    library(shiny)
    
    ui <- fluidPage(
      selectInput("p","p",choices = names(mtcars)),
      plotOutput("myplot"))
    
    server <- function(input, output, session) {
    
      output$myplot <- renderPlot({
        boxplot(mpg ~ get(input$p) , data=mtcars)
      })
    }
    
    shinyApp(ui, server)
    

    【讨论】:

    • 这意味着,当我要选择/引用数据框中命名列中的所有值时,我需要使用 get 函数?
    【解决方案2】:

    boxplot 期望 boxplot(mpg ~ cyl , data=mtcars)input$p 将返回如下字符向量

    Browse[1]> input$p
    [1] "mpg"
    

    一种解决方案是使用as.formula

    library(shiny)
    
    ui <- fluidPage(
      #use setdiff to avoid this Error 'Error in .subset2: attempt to select less than one element in integerOneIndex'
      selectInput("p","p",choices = setdiff(names(mtcars),"mpg")),
      plotOutput("myplot"))
    
    server <- function(input, output, session) {
    
      output$myplot <- renderPlot({
        m <- paste0('mpg','~',input$p)
        boxplot(as.formula(m) , data=mtcars)
      })
    }
    
    shinyApp(ui, server)
    

    要获得更多解释/见解,请参阅question

    【讨论】:

    • 谢谢 A. Suliman,我对 R 的掌握不是很好,所以对我来说,您的解决方案有点复杂。但我正在努力阅读和理解它
    【解决方案3】:

    如果你有机会,也许你想看看库 ggplot2。他们有非常非常好的和易于使用的功能和漂亮的情节。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多