r - 模块化具有多个输出 ID 的闪亮代码
问题描述
我在 Shiny 应用程序中有许多 outputID:
在下面的示例中,我只有三个 outputID
SERVER:
outIDs <- paste("text",1:3)
lapply(list("text1", "text2", "text3"), function(x){
output[[x]] <- renderText({
switch(x,
"text1" = "This is text 1",
"text2" = "This is text 2",
"text3" = "This is text 3"
)
})
})
UI:
lapply(outIDs), function(x) htmlOutput(x))
它可以渲染,但是如果我有 30 个,那么压缩代码的最佳方法是什么?我试过这个
SERVER:
outIDs <- paste("text", 1:30)
outText<- paste("This is test", 1:30)
for (i in 1: length(outIDs ){
output[[outIDs[i]]] <- renderText({
outText[i]
})
UI:
lapply(outIDs), function(x) htmlOutput(x))
通过上述方法,它呈现这个:
“这是文本 30” “这是文本 30”
.... 30 次。
相反,我想要:
“这是文本 1”。“这是文本 2” ... “这是文本 30”
感谢您的帮助,谢谢!
解决方案
请参阅以下内容(使用lapply
而不是 for 循环):
library(shiny)
outIDs <- paste("text", 1:30)
outText <- paste("This is test", 1:30)
ui <- fluidPage(lapply(outIDs, function(x)
htmlOutput(x)))
server <- function(input, output, session) {
lapply(seq_along(outIDs), function(i) {
output[[outIDs[i]]] <- renderText({
outText[i]
})
})
}
shinyApp(ui, server)
作为替代方案,您可以使用它local({ })
来使循环工作(请参阅以下链接)。
在这里,您可以找到有关闪亮的反应和循环的一些信息。
在示例 3 中,Joe Cheng 解释了有关 for 循环的行为如下:
# --- Joe on this behavior:
# --- > It's because all the iterations of the for loop share the same
# --- > reference to el. So when any of the created reactive expressions
# --- > execute, they're using whatever the final value of el was.
推荐阅读
- ios - Xcode - 水平堆栈约束的垂直堆栈
- socialengine - PHP SocialEngine 中新页面的路径
- c - C 程序将元素插入数组,直到用户输入 0 或更少的数字
- python - 发送图像作为响应时出错 [FLASK]
- qt-creator - 添加小部件时 QtCreator 停止工作
- reactjs - React 通用集合钩子函数,适用于多个钩子
- java - 在使用 Myfaces 2.3 的 WAS 8.5.5.16 中面临问题“初始化 MyFaces 时发生错误”
- regex - 正则表达式 - 使用负前瞻排除模式
- node.js - 与 console.log 相比,使用 fs.writeFile 编写的文件有额外的新行。为什么?
- postgresql - 如何在 Postgres 表中插入一个具有一个键的 hstore 值和一组作为对应值的值?