How to select variables for plotting using text box input?

Hello,

I would like to be able to use a text box input to select which variables will be plotted by the pairs.panels() method (similarly to how people define what pages to be printed by a printer). For example I would like to be able to enter in the box the following:
1,3:4,6 in order to plot the pair correlations of variables 1,3,4 and 6.

Thank you!

library(shiny)

df <- data.frame(v1 = c(1,2,3),
                 v2 = rnorm(3),
                 v3 = rnorm(3),
                 v4 = rnorm(3),
                 v5 = rnorm(3),
                 v6 = rnorm(3))

ui <- fluidPage(

    sidebarLayout(
        sidebarPanel(
            textInput("subset", label = "Variables subset:")
        ),

        mainPanel(
           plotOutput("plot"),
           verbatimTextOutput("text")
        )
    )
)

server <- function(input, output) {
    
    # This is to test what the string from the text box looks like
    output$text <- renderPrint({
        col_sel <- input$subset
        col_sel <- paste("c(", input$subset, ")", sep = "")
        print(col_sel)
    })
    
    output$plot <- renderPlot({
        col_sel <- paste("c(", input$subset, ")", sep = "")
        pairs.panels(df[,col_se],                                      # THIS DOES NOT WORK
                     method = "pearson",
                     hist.col = "#FCF928",
                     density = TRUE
        )

    })
}

shinyApp(ui = ui, server = server)
library(shiny)
library(psych)
library(rlang)
library(stringr)
df <- data.frame(v1 = c(1,2,3),
                 v2 = rnorm(3),
                 v3 = rnorm(3),
                 v4 = rnorm(3),
                 v5 = rnorm(3),
                 v6 = rnorm(3))

ui <- fluidPage(
  
  sidebarLayout(
    sidebarPanel(
      textInput("subset", label = "Variables subset:")
    ),
    
    mainPanel(
      plotOutput("plot"),
      verbatimTextOutput("text")
    )
  )
)

server <- function(input, output) {
  
  # This is to test what the string from the text box looks like
  output$text <- renderPrint({
    col_sel <- input$subset
    col_sel <- paste("c(", input$subset, ")", sep = "")
    print(col_sel)
  })
  
  output$plot <- renderPlot({
    req(input$subset)
    if(!str_ends(input$subset,"\\d"))
      return(NULL)
    if(!str_starts(input$subset,"\\d"))
      return(NULL)
    col_sel <- parse_expr(paste("df[,c(", input$subset, ")]", sep = ""))

    local_df <- eval(col_sel)
    if(!isTruthy(local_df))
      return(NULL)
    if(!ncol(local_df)>1)
      return(NULL)
    pairs.panels(local_df,                           
                 method = "pearson",
                 hist.col = "#FCF928",
                 density = TRUE
    )
    
  })
}

shinyApp(ui = ui, server = server)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.