dbo
dbo

Reputation: 1234

if/ifelse statements in renderPlot() for a Shiny app (elementary)

I'm missing some fundamentals with R if statements and especially how they can be used in the server block of a Shiny app. I'm looking just to have a radio button for each of four plots, but I think my if statement structure is failing. Only the last radio button brings up a plot. I'm more familiar with ifelse() but am going off the Shiny template of another - can I use ifelse() here? Also, any help in how to add the input data (data.frame creation and plot definition) into the server block would also be greatly appreciated -- I'm missing something there as well.

library(shiny)
library(ggplot2)

x <- seq(1:100)
y <- rnorm(100)
df <- data.frame(x,y)

p1 <- ggplot(df, aes(x,y)) + geom_line()
p2 <- ggplot(df, aes(x,y)) + geom_point()
p3 <- ggplot(df, aes(x,y)) + geom_bar(stat = "identity")
p4 <- ggplot(df, aes(x,y)) + geom_smooth()

ui <- fluidPage(theme=shinytheme("sandstone"),
            fluidRow(
              column(width=8,
              radioButtons("radioInput", "Radio Button Header", choices =
                  c("name of plot 1 for user" = "plot 1",
                    "name of plot 2 for user" = "plot 2",
                    "name of plot 3 for user" = "plot 3",
                    "name of plot 4 for user" = "plot 4"
                    ))
                    )
            ),             
            plotOutput("distPlot", height="700px")
)

server <- function(input, output) {

output$distPlot <- renderPlot({

    if (input$radioInput == "plot 1")  {p1}   
    if (input$radioInput == "plot 2")  {p2}  
    if (input$radioInput == "plot 3")  {p3}  
    if (input$radioInput == "plot 4")  {p4}

  })
}  

shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 3549

Answers (1)

arg0naut91
arg0naut91

Reputation: 14764

You have two options, either you put print command when plotting:

server <- function(input, output) {

  output$distPlot <- renderPlot({

    if (input$radioInput == "plot 1")  {print(p1)}   
    if (input$radioInput == "plot 2")  {print(p2)}  
    if (input$radioInput == "plot 3")  {print(p3)}  
    if (input$radioInput == "plot 4")  {print(p4)}

  })
}  

Or you go for if/else statements:

server <- function(input, output) {

  output$distPlot <- renderPlot({

    if (input$radioInput == "plot 1")  {p1}   
    else if (input$radioInput == "plot 2")  {p2}  
    else if (input$radioInput == "plot 3")  {p3}  
    else {p4}

  })
}  

Upvotes: 1

Related Questions