用于renderImage的闪亮环境 [英] Shiny environment to use for renderImage
本文介绍了用于renderImage的闪亮环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个框列表,每个框的内部都有一个renderImage
,如下所示:
images = ["i1.png", "i2.png", "i3.png"]
for(i in 1:3){
print(i)
q_list[[i]] = box(
width = 12,
status = "primary",
renderImage({
print(i)
img_path = images[i]
print(img_path)
list(src = img_path, alt = "This is alternate text")},
deleteFile = F)
)
}
不幸的是,这些框似乎没有在循环中注册i
。在上面,它打印的第一个i
是正确的(1-2-3)。但第二个i
,renderImage
内的打印为3,img_path
为i3.png
。我是否需要将其他环境设置为renderImage
才能正常工作?
按照注释的要求,这里是一个最小的示例。主板在以下三个框中显示相同的图形(i3.png):
rm(list = ls(all.names = TRUE))
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(shinybusy)
library(shinyjs)
options(shiny.error = browser)
options(shiny.fullstacktrace = TRUE)
options(shiny.trace = TRUE)
images = c("i1.png", "i2.png", "i3.png")
ui = dashboardPage(
sidebar = dashboardSidebar(disable = T),
body = dashboardBody(uiOutput("module_body")),
header = dashboardHeader(disable = T)
)
server = function(input, output, session){
imgs_fct = function(){
im_list = list()
for(i in 1:3){
print(i) # prints correctly
img_path = images[i] # prints correctly
print(img_path)
# store each box in im_list
im_list[[i]] = box(
width = 12,
status = "primary",
renderImage({
print(img_path) # prints "i3.png"
list(src = img_path, alt = "This is alternate text")}, deleteFile = F)
)
}
return(im_list)
}
output$module_body = renderUI({
theitems = tabItem(tabName = "xxx", fluidRow(column(width = 8, offset = 2, id = "form", imgs_fct())))}
)
}
# run the app
shinyApp(ui = ui, server = server)
推荐答案
如注释中所示,如果您在imgs_fct
函数中使用lapply
,这将按预期工作,每个绘图都会按预期呈现,而不仅仅是所有绘图的最终绘图。请注意,images
是指向图像的文件路径的矢量,因此假设它们与您漂亮的应用程序代码位于同一目录中:
imgs_fct = function(){
lapply(images,
function(x) {
box(
width = 12,
status = "primary",
renderImage({
list(src = x, alt = "This is alternate text")}, deleteFile = F)
)
})
}
这种方法起作用而for
循环不起作用的原因是,您用来迭代的计数器(这里是i
)在所有renderImage
调用之间是共享的,因为它们在相同的环境中(因为它们在同一个循环中)。发生的情况是,计算运行,然后当SHINY在此过程结束时尝试解析任何反应性依赖关系时,所有render
函数共享相同的引用i
,此时该引用等于3,因此所有函数都使用相同的图像呈现。
lapply
中,每个renderImage
都在单独的函数调用中,因此在单独的环境中求值,其中每个函数都有一个不同的图像文件路径作为参数。因此,正如您所期望的那样,这些都是单独渲染的。您可能会将for
循环的内容包装在local({})
中,但我个人喜欢lapply
方法,因为它看起来更像是‘R’-y。
这篇关于用于renderImage的闪亮环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文