Home > database >  How to select a column from a dynamic input variable?
How to select a column from a dynamic input variable?

Time:03-17

I'm using flexdashboard and shiny to choose which variable to plot:

varSelectInput("button_var_fir"
               , "Select first num variable"
               , data = df_scat,
                multiple = FALSE
               )

ggplot(df_scat, aes(x = !!input$button_var_fir, y = Gen_type, fill = stat(x)))  
  geom_point(size= 3, alpha = .075) 

it works fine, so far. My problem is, that I would like to subset the data e.g via

df$variable > 0
ggplot(df_scat, aes(x = df$!!input$button_var_fir > 0, y = Gen_type, fill = stat(x)))  
      geom_point(size= 3, alpha = .075) 

but this doesn't work due to the $!!. How can I solve this?

CodePudding user response:

Maybe what you want is

df[[input$button_var_fir]] > 0

instead of df$!!input$button_var_fir > 0.


Addition:
You want to subset the data that goes into the plot, right? What I would actually do is subsetting the dataframe itself before it goes into the plot function. When you use the tidyverse this could be what you want:

df_scat %>%
    filter(!!input$button_var_fir > 0) %>%
    ggplot(aes(x = !!input$button_var_fir, y = Gen_type, fill = stat(x)))  
    geom_point(size= 3, alpha = .075) 

CodePudding user response:

You can use the .data pronoun to dynamically select variables. Here's a small example:

library(tidyverse)
library(shiny)

ui <- fluidPage(titlePanel("Dynamic Variable Selection"),
                sidebarLayout(sidebarPanel(
                  selectInput(
                    inputId = "y1",
                    label = "Select variable",
                    choices = names(mtcars))),
                mainPanel(plotOutput(outputId = "plot"))))

server <- function(input, output) {
  output$plot <- renderPlot({
    mtcars %>%
      ggplot(aes(x = .data[[input$y1]]))  
      geom_histogram()})}

shinyApp(ui = ui, server = server)
  • Related