我正在尝试开发一个闪亮的应用程序,用户可以上传csv文件,随后由我的R脚本进行分析。因此,我希望根据处理的文件数量显示动态数量的图表(每个文件一个图表)。
我发现this问题非常有帮助,但我事先并不知道最大数量的情节。这是我试过的:
shinyServer(function(input, output) {
# Insert the right number of plot output objects into the web page
output$densityPlots <- renderUI({
plot_output_list <- lapply(1:length(input$file1$datapath), function(i) {
plotname <- paste("densityPlot", i, sep="")
plotOutput(plotname)
})
# Convert the list to a tagList - this is necessary for the list of items
# to display properly.
do.call(tagList, plot_output_list)
})
# Call renderPlot for each one. Plots are only actually generated when they
# are visible on the web page.
for (i in 1:length(input$file1$datapath)) {
# Need local so that each item gets its own number. Without it, the value
# of i in the renderPlot() will be the same across all instances, because
# of when the expression is evaluated.
local({
my_i <- i
plotname <- paste("densityPlot", my_i, sep="")
output[[plotname]] <- renderPlot({
plot(1)
})
})
}
}
然而,它给了我这个错误:
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
我试图将for-loop放在输出函数中,但是根本没有创建绘图。
答案 0 :(得分:3)
我可以让它发挥作用。必须使用反应导体来创建图,如here
所述shinyServer(function(input, output) {
createPlots <- reactive ({
numberOfFiles <- length(input$files$datapath)
for (i in 1:numberOfFiles) {
local({
my_i <- i
plotname <- paste("plot", my_i, sep="")
File <- read.csv(input$files$datapath[my_i])
output[[plotname]] <- renderPlot({
result <- runDensity(File, f)
plot(result$data, main=id, pch=19,cex=0.2, col= ColoursUsed[result$clusters])
})
})
}
})
output$densityPlot <- renderUI({
inFile <- input$files
if (is.null(inFile))
return(NULL)
createPlots()
numberOfFiles <- length(inFile$datapath)
plot_output_list <- lapply(1:numberOfFiles, function(i) {
plotname <- paste("plot", i, sep="")
plotOutput(plotname)
})
do.call(tagList, plot_output_list)
})
})