复制此问题的简单方法:
shinyApp(
ui = fluidPage(
textOutput("helloJohn"),
br(),
textOutput("helloJacob"),
br(),
textOutput("helloJoe")),
server = function(session, input, output) {
for(name in c("John", "Jacob", "Joe")) {
output[[paste0("hello", name)]] <- renderText({paste0("hello ", name, "!")})
}
})
此代码的目的是让文本“Hello John”、“Hello Jacob”、“Hello Joe”出现在页面上,而不必重用 renderText
block 。然而,虽然输出名称似乎设置正确,但在渲染时,name
似乎被设置为 for 循环中的最后一个值,导致所有名称均为“Joe”:
我认为这是由于 Shiny 设置依赖图的方式造成的,但是 name
不是 react 变量,它在初始化期间可用。有没有一种方法可以强制在 for 循环内评估 name
,类似于 Haskell 中的 Bang 模式?
最佳答案
您可以将 for 循环中的内容包装在 local
中,并创建一个接收 name
的局部变量 name2
。
for(name in c("John", "Jacob", "Joe")) {
local({
name2 <- name
output[[paste0("hello", name2)]] <- renderText({paste0("hello ", name2, "!")})
})
}
此答案的其他信息和灵感 here .
关于R Shiny 的 for 循环变量依赖不良。有没有办法强制评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43762513/