Matt.TW
Matt.TW

Reputation: 105

R: Referring to a variable name with special characters

For a Shiny program I'm writing, I have input variables that contain a dash, commas and brackets. Spaces I can substitute out but the rest are needed since they are refering to chemical compounds and don't make sense without them. As expected, these characters make the Shiny app unable to find the desired variable; whilst variables with none of these characters work fine.

EDITED: The code below is a test Shiny app. With Chemical-X(a,b) the app returns "could not find function X". With Chemical.B the app returns "object Chemical.B not found" which is the desired result since the app sees the chemical as an object and not some function that doesn't exist.

library (shiny)
library (ggplot2)

dat <- as.data.frame(c("Chemical-X(a,b)", "Chemical.B"))
dat[,2] <- (c(6,3)) 
colnames(dat) <- c("Chemical", "Count")

ui <- fluidPage(

 titlePanel("SE Test"),
  sidebarLayout(
   sidebarPanel(
    selectInput(inputId = "varX",
              label = "Chemical",
              choices = dat[,1],
              width = "200px"),
    selectInput(inputId = "varY1",
              label = "Count",
              choices = dat[,2],
              width = "200px")
  ),
mainPanel(
  plotOutput("chemPlot")
   )
  )
 )
server <- function(input, output){

 output$chemPlot <- renderPlot({
  plot.data <- ggplot(data = dat)
    point <- plot.data + geom_point(
    aes_string(x = input$varX, y = input$varY1))
  plot(point)
  })

}

shinyApp(ui = ui, server = server)

Is there a known way of doing this or will I need to come up with some viable work around? I have tried using backticks as suggested here but this hasn't worked.

Thanks, Matt

Upvotes: 2

Views: 3744

Answers (2)

alan ocallaghan
alan ocallaghan

Reputation: 3038

I have found that backticks and aes_string usually works for me.

library("ggplot2")
my_dodgy_var <- "name with~special character"
mtcars[[my_dodgy_var]] <- mtcars$cyl
ggplot(mtcars, aes_string(x=paste0("`", my_dodgy_var, "`"), y="mpg")) + 
  geom_point()

I often use a helper function paste_aes to do this, eg:

paste_aes <- function(x) paste0("`", x, "`")

Upvotes: 4

Matt.TW
Matt.TW

Reputation: 105

I've fixed it now by calling as.name the Shiny input$ variable. For the example above it would look like this.

 server <- function(input, output){

 output$chemPlot <- renderPlot({
  plot.data <- ggplot(data = dat)
    point <- plot.data + geom_point(
    aes_string(x = as.name(input$varX), y = as.name(input$varY1)))
  plot(point)

This appears to work now as intended. Thank you aocall for your efforts.

Upvotes: 5

Related Questions