SelectInput无法识别带连字符的名称

时间:2020-07-30 20:17:15

标签: r shiny shinydashboard

我对闪亮的Select输入有问题,如果sb可以帮忙,我将不胜感激。我正在尝试创建一个绘图,用户可以在该绘图上根据自己的要求更改图表的颜色。似乎如果以某种方式在Selectinput中输入的名称带有连字符,则renderplot将不返回任何内容。当我从名称中删除连字符(例如A2019而不是A-2019)时,renderplot返回正确的图并且一切正常。我已经尝试了几个小时来修复它,但没有成功。我的语法出了什么问题?



gg_fill_hue <- function(n) {
  hues = seq(15, 375, length = n + 1)
  hcl(h = hues, l = 65, c = 100)[1:n]
}

Complete_1 <- data.frame(
  title    = c("A-2019", "B-2018", "C-2017","D-2018","E-2019","F-2020"), 
  partner  = c("A", "A", "B","B","C","C"), 
  quantity = c(100, 200, 300,400,500,600)
)



library(shinydashboard)
library(shiny)
library(jsonlite)
library(shinyWidgets)
library(plotly)
library(colourpicker)
library(tidyverse)


###  UI ----


header <- 
  dashboardHeader( title = HTML("Dashboard"), 
                   disable = FALSE, 
                   titleWidth  = 230)


sidebar <- dashboardSidebar(
  sidebarMenu(id="sbmenu",
              menuItem("General Dashboard", tabName = "dashboard", icon = icon("dashboard"))))


body <- dashboardBody( 
  
  tabItems(
    tabItem(tabName = "dashboard",
            fluidRow(
              
              selectizeInput("choice",p("Please select title:",style="color:black; text-align:center"),
                          choices=levels(Complete_1$title),multiple=T)),
            
            fluidPage(
              uiOutput("myPanel"),
              plotOutput("plot")))))





## UI wrapper -----


ui <- dashboardPage(header, sidebar, body)


## Server ----

server <- function(input, output) {
  
  data_complete <- reactive({Complete_1 %>% 
      filter(title%in%input$choice)})
  
  
  ### Plot 

  
  
  output$myPanel <- renderUI({ 
    
    lev <- sort(unique(input$choice)) 
    
    cols <- gg_fill_hue(length(lev))
    
    
    dropdownButton(lapply(seq_along(lev), function(i) {
      colourpicker::colourInput(inputId = paste0("col", lev[i]),
                                label = paste0("Choose colour for", lev[i]), 
                                value = cols[i])}),
      circle = TRUE, size="xs",status = "danger", icon = icon("gear"), width = "50px",
      tooltip = tooltipOptions(title = "Change your colour"))
  })
  
  
  output$plot <- renderPlot({
    
    cols <- paste0("c(", paste0("input$col",sort(input$choice), collapse = ", "), ")")
    
    cols <- eval(parse(text = cols))
    
    req(length(cols) == length(input$choice)) 
    
    
    data_complete() %>% 
      group_by(title,partner) %>% 
      summarise(total=sum(quantity)) %>% 
      ggplot(aes(x=partner,y=total,fill=title))+
      geom_col(stat="identity",position = position_dodge())+
      scale_fill_manual(values = cols)
  })  
  
  
  
}


shinyApp(ui, server)

1 个答案:

答案 0 :(得分:1)

该问题与SelectInput不接受带连字符的名称无关。通常,如果要使用连字符或空格来命名变量或列出元素或数据框列,或者...,则必须将名称放在反引号“`”中。

因此,在renderPlot内的粘贴语句中添加反引号即可解决此问题。试试这个:

cols <- paste0("c(", paste0("input$`col", sort(input$choice), collapse = "`, "), "`)")