gpt4 book ai didi

R Shiny - 如何在 selectInput 中显示选择标签

转载 作者:行者123 更新时间:2023-12-03 22:19:28 25 4
gpt4 key购买 nike

我定义了一个 selectInput 如下。我想访问每个选项的标签,并将其呈现在主面板上。

如果用户选择“Sugar sweetened bev.”,我想在主面板上呈现如下内容:

“你选择了加糖的 bev。”,但我得到的是“你选择了 ssb”。

我以这种方式设置 selectInput 选项的原因是因为我想要图表标题的左侧,而右侧是变量名称。

非常感谢任何建议或替代方向!

 library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("foodvars", "Select food:",
choices = c("Beef/Pork" = "beefpork",
"Sugar sweeteened bev." = "ssb",
"Total fruit" = "total_fruit"))),
mainPanel(
textOutput("dispText")))
)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("foodvars", "Select food:",
choices = c("Beef/Pork" = "beefpork",
"Sugar sweeteened bev." = "ssb",
"Total fruit" = "total_fruit"))),
mainPanel(
textOutput("dispText")))
)
server <- function(input, output) {

output$dispText <- renderText({
paste("You chose ",input$foodvars)})
}

shinyApp(ui = ui, server = server)

最佳答案

我们全局创建相同命名的向量,然后在逻辑 names 上使用 vector 检索名称

library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("foodvars", "Select food:",
choices = c("Beef/Pork" = "beefpork",
"Sugar sweeteened bev." = "ssb",
"Total fruit" = "total_fruit"))),
mainPanel(
textOutput("dispText")))
)

choiceVec <- c("Beef/Pork" = "beefpork",
"Sugar sweeteened bev." = "ssb",
"Total fruit" = "total_fruit")

server <- function(input, output) {

output$dispText <- renderText({

paste("You chose ",names(choiceVec)[choiceVec == input$foodvars])})
}

shinyApp(ui = ui, server = server)

-输出

enter image description here

关于R Shiny - 如何在 selectInput 中显示选择标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48106504/

25 4 0