r - 用于 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
is i3.png
。我是否需要放置另一个环境才能renderImage
使其正常工作?
正如评论中所要求的,这里是一个最小的例子。仪表板在 3 个框中显示相同的图形 (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)
解决方案
正如评论中所建议的,如果您lapply
在imgs_fct
函数中使用,这将按预期工作,每个图都按预期呈现,而不仅仅是所有图的最终图。请注意,这images
是图像文件路径的向量,因此假设它们与您的 Shiny 应用程序代码位于同一目录中:
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。
推荐阅读
- ios - 尝试从 json 数据加载图像 url 时索引超出范围
- groovy - methodMissing 的 Groovy 缓存不起作用
- node.js - npx create-react-app 返回“超出最大调用堆栈大小”
- latex - 如何在 p5.js 中显示漂亮的数学方程式?
- kubernetes-helm - 是否有任何选项告诉 helm 不要等到安装后挂钩完成?
- sql - 执行存储在表列中的 SQL 语句
- python - 存储 flask-jwt 身份验证令牌。我可以/我应该存储在数据库中吗?
- python - 当我尝试运行代码时,它会出错
- bigcommerce - 有没有办法从 BigCommerce 的单个页面中删除站点导航?
- java - 如何配置 WireMock 以将 StubMappings 加载/保存到 AWS S3?