我在 shiny 中使用 selectInput,在我选择的下拉菜单中,我希望某些单词之间有多个空格。但是只包含空格不会显示,在应用程序中最多有一个空格。
例如在下面的代码示例中,我在“Cylinder”和“I”之间有多个空格,但是如果您运行它,只会显示一个 - 我该如何解决这个问题?
ui <- fluidPage(
selectInput("variable", "Variable:",
c("Cylinder I want multiple spaces here" = "cyl",
"Transmission" = "am",
"Gears" = "gear")),
tableOutput("data")
)
server <- function(input, output) {
output$data <- renderTable({
mtcars[, c("mpg", input$variable), drop = FALSE]
}, rownames = TRUE)
}
shinyApp(ui, server)
}
最佳答案
我通常将空格 (ASCII 32) 替换为“硬空间”(ASCII 160)。 在这种情况下,未检测到多个空格。
由于 RStudio 不接受 ALT-160 作为“”,因此需要使用 intToUtf8(160)
动态注入(inject)符号 160。
注意:base::strrep()
无法正确处理符号 160,因此必须改用 stringi::stri_dup()
。
感谢您建议将生成的名称放入 selectInput()
中的意见。得到的解决方案如下:
library(shiny)
library(shinydashboard)
library(stringi)
# Praparations (could be put into global.R) ------------
choices <- c(
"TO BE OVERRIDEN" = "cyl",
"Transmission" = "am",
"Gears" = "gear")
# Replace name place holder with the actual one
names(choices)[1] <- paste0(
"Cylinder",
stri_dup(intToUtf8(160), 6), # Replace 6 with the desired number
"I want multiple spaces here")
# Definition of UI -----------
ui <- fluidPage(
selectInput("variable", "Variable:", choices),
tableOutput("data")
)
# Definition of server -----------
server <- function(input, output) {
# Main table
output$data <- renderTable({
mtcars[, c("mpg", input$variable), drop = FALSE]
}, rownames = TRUE)
}
# Run app -------
shinyApp(ui, server)
如果有道理,请告诉我。
关于html - selectInput 选择显示标签中 Shiny 的额外空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40513153/