Antjes
Antjes

Reputation: 120

Select dynamically a dataframe subset

I am having issues to be able to subset dynamically a dataframe by the column selected in a dropdown menu. Basically, I want to allow the user to decide which one is going to be the column to be on the y axis.

File global.R:

library(shiny)
library(plotly)

# Cars
data("USArrests")
USArrests$state <- row.names(USArrests)

File ui.R:

ui <- fluidPage(
    fluidRow(
        selectInput(inputId = "select_col",
                    label = tags$h4("Select Column"),
                    choices = c("Murder", "Assault", "UrbanPop", "Rape"),
                    selected = "Murder"
        ),
        plotlyOutput("plot")
    )
)

File server.R:

server <- function(input, output) {
    output$plot <- renderPlotly({
        plot_ly(USArrests, 
                x = ~state,
                y = ~input$select_col, # this works but is not reactive y = ~Murder
                type = 'bar')
        
    })   
}

Here on this last file is the problem that I am having. It is not accepting as a valid input the value from the select_col dropdown menu (y = ~input$select_col).

Bad Solution:

I have come up with this solution, bad I do not like it. It is too verbose. There is a more efficient way to do it?

Corrected server.R:

server <- function(input, output) {
    output$plot <- renderPlotly({
        df <- USArrests[c('state', input$select_col)]
        names(df) <- c('state', 'to_y')
        plot_ly(df, 
                x = ~state,
                y = ~to_y, 
                type = 'bar')
        
    })   
}

Upvotes: 1

Views: 86

Answers (1)

r2evans
r2evans

Reputation: 160447

One option is to generate the formula programmatically:

server <- function(input, output) {
    output$plot <- renderPlotly({
        plot_ly(USArrests, 
                x = ~state,
                y = formula(paste("~", input$select_col)),
                type = 'bar')
        
    })   
}

Upvotes: 2

Related Questions