在r Shiny中,使用stats :: setNames将名称分配给向量元素,然后检索服务器端的名称属性
我有一个闪亮的应用程序显示数据库中的数据,其中分配了变量的代码(例如,对于最高温度,“ tmax”,“ GDD”,用于增长的天数等)。用户将选择要从SelectInput显示的变量,然后使用Stats :: SetNames()
将名称分配给选择向量的元素。在该应用程序的完整版本中,创建了数字,以显示所选变量的数据,我希望能够将元素的名称用作图的Y-Label(例如,如果变量为Tmax,则我希望y轴显示“最大温度”)。我分配的名称出现在SelectInput下拉中,但是当用户实际选择一个选项时,名称属性似乎会丢失。当我在选定输入上调用name()
时,它返回null
。
这个迷你应用显示了问题。 (我只是在打印和渲染变量的名称,而不是创建名称为标签的数字。)
library(shiny)
ui <- fluidPage(
selectInput(
'select', 'Select',
choices = stats::setNames(
object = c('var1', 'var2', 'var3'),
nm = c('Variable 1', 'Variable 2', 'Variable 3')
)
),
textOutput('var'),
textOutput('varname')
)
server <- function(input, output, session) {
observeEvent(input$select, {
print(names(input$select))
output$var <- renderText(paste('Variable:', input$select))
output$varname <- renderText(paste('Variable name:', names(input$select)))
})
}
shinyApp(ui, server)
谢谢!
I have a shiny app that displays data from a database, in which variables are assigned codes (e.g., "TMAX" for maximum temperature, "GDD" for growing degree days, etc). The user will pick a variable that they want to display from a selectInput, and I assigned names to the elements of the choices vector using stats::setNames()
. In the full version of the app, figures are created displaying data for the selected variable, and I want to be able to use the name of the element as the y-label for the plot (for example, if the variable is TMAX, then I want the y axis to display "Max Temperature"). The names that I've assigned appear in the selectInput dropdown, but the name attribute appears to be lost when the user actually selects an option; when I call names()
on the selected input, it returns NULL
.
This mini app shows the issue. (I'm just printing and rendering the name of the variable rather than creating a figure with the name as the label.)
library(shiny)
ui <- fluidPage(
selectInput(
'select', 'Select',
choices = stats::setNames(
object = c('var1', 'var2', 'var3'),
nm = c('Variable 1', 'Variable 2', 'Variable 3')
)
),
textOutput('var'),
textOutput('varname')
)
server <- function(input, output, session) {
observeEvent(input$select, {
print(names(input$select))
output$var <- renderText(paste('Variable:', input$select))
output$varname <- renderText(paste('Variable name:', names(input$select)))
})
}
shinyApp(ui, server)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
多亏了@smokeyshakers,我进行了以下更改(在哈希之间):
Thanks to @SmokeyShakers, I made the following changes (between the hashes):