简体   繁体   English

r一个循环中闪亮的renderUI

[英]r shiny renderUI in a loop

I'd like to output several tables as a one uiOutput. 我想输出几个表作为一个uiOutput。 If I put them together in a list using a loop then all outputs are equal to the last one. 如果我使用循环将它们放在一个列表中,那么所有输出都等于最后一个。 Example: 例:

library(shiny)

ui <- fluidPage(
  mainPanel(
    uiOutput("tables")
  )
)

server <- function(input, output) {
  output$tables <- renderUI({
    data=array(rnorm(150),c(10,5,3))

    tfc = function(m){
#      x = m[1,1]
      renderTable({m})
    }

    result=list()
    for(i in 1:3)
      result[[i]] = tfc(data[,,i])

    return(result)
  })
}

shinyApp(ui = ui, server = server)

If I remove the commented line (x = m[1,1]) I get the desired result. 如果我删除注释行(x = m [1,1]),我会得到所需的结果。

I can live with this workaround but is there a reason why shiny behaves like that or is there a different way to do it? 我可以忍受这种解决方法但是有一个原因可以解释为什么闪亮的表现或者有不同的方法来做到这一点?

I usually use lapply for such usecases. 我通常使用lapply这样的用例。 This way, you don't run into issues with lazy evaluation. 这样,您就不会遇到延迟评估的问题。

library(shiny)

ui <- fluidPage(
  mainPanel(
    uiOutput("tables")
  )
)

server <- function(input, output) {
  output$tables <- renderUI({
    data=array(rnorm(150),c(10,5,3))

    tfc = function(m){renderTable({m})}

    lapply(1:3, function(i){tfc(data[,,i])})
  })
}

shinyApp(ui = ui, server = server)

If you want to use a reacive table, you can use something like 如果你想使用一个反应表,你可以使用类似的东西

tfc = function(m, output, id){
  output[[id]] <- renderTable({m()})
  tableOutput(id)
}

instead. 代替。

To get around this, you can force evaluation of function arguments: 要解决这个问题,您可以force评估函数参数:

tfc = function(m) {
  force(m)
  renderTable(m)
}

or 要么

create a local scope for each loop iteration: 为每个循环迭代创建一个local范围:

for (i in 1:3) {
  local({
    i <- i
    result[[i]] <<- tfc(data[,,i])
  })
}

lapply works as well, but only for R versions 3.2 and above: https://cran.r-project.org/bin/windows/base/old/3.2.0/NEWS.R-3.2.0.html lapply适用,但仅适用于R版本3.2及以上版本: httpslapply

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM