【问题标题】:R shiny - Extract nested vector from dynamic tab listR shiny - 从动态选项卡列表中提取嵌套向量
【发布时间】:2021-03-06 22:21:58
【问题描述】:

实际上我是第一次在闪亮的应用上工作。

基于上传的 xlsx,闪亮的应用程序创建一个名为 garnetRF() 的响应式输出。根据上传的 xlsx 中不同命名样本的数量,应用程序会在 output$tabp 中创建动态选项卡。在选项卡中,用户可以选择要为每个样本显示的颜色。到目前为止,一切顺利。

现在,在输出$设置中,我想用用户选择的颜色绘制结果。因此,我的想法是通过选择的颜色名称 (cls.1) 重命名样本级别 (cls.0)。但是,当执行以下代码时, print(cls.1) 会显示空列表和包含颜色代码的向量。我猜这是因为 colorInput 嵌套在动态选项卡列表中。

有人知道如何只提取颜色向量吗?

output$tabp <- renderUI({
    req(garnetRF())
    l = length(unique((garnetRF()[,"sample"])))
    
    myTabs <- lapply(1:l, function(i) {
      tabPanel(title = as.list(factor(unique(garnetRF()[,"sample"])))[[i]],
               colourInput(paste0("col_", i), NULL, paste0("FF000", i), showColour = "background")
      )
    })
    do.call(tabsetPanel, myTabs)
  })
  
  output$setting <- renderPlot({
    req(garnetRF())
    l2 = length(unique((garnetRF()[,"sample"])))
    cls.0 = factor(garnetRF()[,"sample"])
    cls.1 = sapply(1:l2, function(j){input[[paste0("col_", j)]]})
    print(cls.1)

结果:

[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[1] "#FF0001" "#FF0002" "#FF0003"

这是一个可重现性极低的示例:

ui <- fluidPage(
  
  titlePanel("Example"),
  
  fluidRow(
    column(8,
           plotOutput("setting"),
    ),
    column(4,
           uiOutput("tabp")
    )
  )
)
server <- function(input, output) {
  
  garnetRF <- reactive({
    mydata = data.frame(
      "sample" = c("example1", "example2", "example3"),
      "A" = (c(30, 30, 30)),
      "B" = (c(40, 30, 20)),
      "C" = (c(30, 40, 50)))
    return(mydata)
  })
  
  output$tabp <- renderUI({
    req(garnetRF())
    l = length(unique((garnetRF()[,"sample"])))
    
    myTabs <- lapply(1:l, function(i) {
      tabPanel(title = factor(unique(garnetRF()[,"sample"]))[[i]],
               colourInput(paste0("col_", i), NULL, paste0("FF000", i), showColour = "background")
      )
    })
    do.call(tabsetPanel, myTabs)
  })
  
  output$setting <- renderPlot({
    req(garnetRF())
    l2 = length(unique((garnetRF()[,"sample"])))
    cls.0 = factor(garnetRF()[,"sample"])
    cls.1 = sapply(1:l2, function(j){input[[paste0("col_", j)]]})
    print(cls.1)
    
    #plot following
    })
}

【问题讨论】:

标签: r shiny


【解决方案1】:

定义cls.1时需要req(),如下所示。

output$setting <- renderPlot({
    req(garnetRF())
    l2 = length(unique((garnetRF()[,"sample"])))
    cls.0 = factor(garnetRF()[,"sample"])
    cls.1 <- sapply(1:l2, function(j){req(input[[paste0("col_", j)]])})
    print(cls.1)
    
    #plot following
    output$plot1 <- renderPlot(plot(cars))
  })

【讨论】:

  • 完美!!!!太感谢你了!!!你能简单解释一下为什么需要 req() 吗?
  • input$col_1 的初始值为NULL。对于req(),直到input$col_1 被定义(所有col_j 相同),cls.1 才被定义。有关更多信息,请参阅此处req()shiny.rstudio.com/reference/shiny/latest/req.html
猜你喜欢
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 2018-04-21
  • 1970-01-01
  • 1970-01-01
  • 2017-04-06
  • 2021-11-05
  • 1970-01-01
相关资源
最近更新 更多