R:使用特殊字符引用变量名 [英] R: Referring to a variable name with special characters

查看:118
本文介绍了R:使用特殊字符引用变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在编写的Shiny程序,我具有包含破折号,逗号和方括号的输入变量.我可以替代的空间,但其余空间是必需的,因为它们是指化合物,没有它们就没有意义.正如预期的那样,这些字符使Shiny应用程序无法找到所需的变量.而没有这些字符的变量都可以正常工作.

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.

已编辑:下面的代码是经过测试的Shiny应用.使用Chemical-X(a,b),应用程序返回找不到功能X".使用Chemical.B,应用程序返回未找到对象Chemical.B",这是所需的结果,因为该应用程序将化学品视为对象,而不是某些不存在的功能.

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,服务器=服务器)

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.

谢谢,马特

推荐答案

我现在通过调用as.name Shiny input $变量来修复它.对于上面的示例,它看起来像这样.

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)

这似乎已按预期工作.谢谢aocall的努力.

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

这篇关于R:使用特殊字符引用变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆