1

I am trying to create/ learn an interactive box plot through Shiny, below id the code i m trying to use. This gives me the error

Warning: Error in model.frame.default: variable lengths differ (found for 'input$p')
[No stack trace available]

I am unable to figure this out, any help would be much appreciated

CODE:

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)
A. Suliman
  • 12,923
  • 5
  • 24
  • 37
Fahadakbar
  • 488
  • 1
  • 8
  • 26

3 Answers3

1

boxplot expect boxplot(mpg ~ cyl , data=mtcars) while input$p will return a character vector as below

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

One solution is to use 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)

To get more explanation/insights see this question

A. Suliman
  • 12,923
  • 5
  • 24
  • 37
  • Thanks A. Suliman, my grip on R is not really great, so for me your solution is kind of complicated. but i am trying to read and understand it – Fahadakbar Oct 01 '18 at 16:54
1

Why dont you just use 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)
Pork Chop
  • 28,528
  • 5
  • 63
  • 77
  • so that means , when ever i am to pick / refer to all the values in a named column in data frame, i need to use get function ? – Fahadakbar Oct 01 '18 at 16:57
0

If you have a chance, maybe you want to check out library ggplot2. They have very very nice and easy to use functions and pretty plot.

Y.Dong
  • 36
  • 8