【发布时间】:2016-11-11 18:00:35
【问题描述】:
在 Shiny htmlOutput 中使用循环是一种非常奇怪的行为。我一直在尝试做的非常简单,从 Shiny htmlOuput 执行 Javascript 代码(console.log)并将循环编号打印到控制台。见以下代码:
library(shiny)
ui <- fluidPage(
actionButton("goButton", "Go!"),
mainPanel(htmlOutput("result"))
)
server<- function(input, output) {
observeEvent(input$goButton,{
output$result <- renderUI({
html_output_list <- lapply(1:50, function(j) {
htmlname <- paste("html", j, sep="")
htmlOutput(htmlname)
})
# Convert the list to a tagList - this is necessary for the list of items
# to display properly.
do.call(tagList, html_output_list)
})
lapply(1:14, function(i){
htmlname <- paste("html", i, sep="")
output[[htmlname]] <- reactive({
paste('<script>number=',
i,
';console.log(number);</script>')
})
})
})
}
shinyApp(ui = ui, server = server)
通过单击 go 按钮,结果应该是从 1 到 14 的有序序列号(因为数字 i 从 1 到 14 循环),但实际结果是 14,1,2,...,13。尝试从 1:20 开始的 i 范围将生成一个序列为 (14,15,16,17,18,1,19,2,3,4,5,6,7,8,20,9,10,11 ,12,13)。谁能解释这里发生了什么?怎么不按顺序?显然这不是随机顺序。
【问题讨论】:
标签: javascript r shiny