【问题标题】:Use selectInput() choice to select data in a R6 Class使用 selectInput() 选择在 R6 类中选择数据
【发布时间】:2023-03-26 23:59:02
【问题描述】:

我试图了解如何在 Shiny 应用程序中使用 R6 类对象,并且我想使用 selectInput() 选项在 R6 对象中呈现数据。选择输入选项包含我的R6 对象的名称。

我有以下物品:

library(R6)
Person <- R6Class("Person", list(
  name = NULL,
  age = NA,
  sons = NA,
  initialize = function(name, age = NA, sons = NA) {
    self$name <- name
    self$age <- age
    self$sons <- sons
  }
))

Manel <- Person$new("Manel", age = 42, sons = c('Joana', 'Gabriel'))
Carla <- Person$new("Maria", age = 44, sons = NA)
Matilde <- Person$new("Matilde", age = 52, sons = c('Bruno', 'Joana', 'Maria'))

在我的 Shiny 应用程序中,我有一个 selectInput(),其中包含 Manel、Carla、Matilde 选项。我需要的是,当我选择一个选项时,我会使用我在 selectInput() 中选择的名称呈现对象的值。下面的闪亮应用:

library(shiny)
ui <- fluidPage(
  sidebarPanel(
    selectInput('names', 'Names', choices = c('Manel', 'Carla', 'Matilde'))
    ),
  mainPanel(
    uiOutput('name'),
    uiOutput('age'),
    uiOutput('sons')
  )
)

server <- function(input, output, session) {
  output$name <- renderText(Manel$name)
  output$age <- renderText(Manel$age)
  output$sons <- renderText(Manel$sons)
}

shinyApp(ui, server)

谢谢!

【问题讨论】:

    标签: r shiny r6


    【解决方案1】:

    input$names 总是只转一个字符值。要从变量的名称中获取变量的值作为字符,您可以使用get() 函数。在这里,我们可以将其包装在一个响应式对象中,因此我们始终可以访问“当前”人员以获取响应式输出。我们可以的

    server <- function(input, output, session) {
      person <- reactive(get(input$names))
    
      output$name <- renderText(person()$name)
      output$age <- renderText(person()$age)
      output$sons <- renderText(person()$sons)
    }
    

    或者,将您的人员存储在命名列表中而不是一堆变量中可能更有意义。例如

    people <- list(
      Manel = Person$new("Manel", age = 42, sons = c('Joana', 'Gabriel')),
      Carla = Person$new("Carla", age = 44, sons = NA),
      Matilde = Person$new("Matilde", age = 52, sons = c('Bruno', 'Joana', 'Maria'))
    )
    

    然后您可以使用 select 中的字符值来索引命名列表,而不是使用get()

    server <- function(input, output, session) {
      person <- reactive(people[[input$names]])
    
      output$name <- renderText(person()$name)
      output$age <- renderText(person()$age)
      output$sons <- renderText(person()$sons)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      相关资源
      最近更新 更多