如何解决R Shiny:使用assign编写无功输出元素的名称失败
我要实现的目标是使用基于单击按钮时触发的计数器的名称来处理动态生成的UI元素。这个工作正常,但是我不能使用assign()组合这些输出元素的名称。这是一个演示问题的简单示例:
library(shiny)
ui <- fluidPage(
actionButton("run_btn","Run"),plotOutput('Plot1'),plotOutput('Plot2'),plotOutput('Plot3')
)
server <- function(input,output,clientData,session) {
observeEvent(input$run_btn,{
myplot <- renderPlot({
boxplot(1:100)
})
assign(paste('output$Plot',sep = "",input$run_btn),myplot) # DOES NOT WORK!
# output$Plot1 <- myplot # THIS WORKS!
})
}
# Run the application
shinyApp(ui = ui,server = server)
解决方法
我推断您想以某种方式叠加添加新图,并可能进行一些清理?
动作:
- 按下
Run
按钮,将创建一个mtcars
的情节,突出显示一个随机的汽车。 - 每次添加一个新地块时,都要重复多次,并堆叠在所有其他地块之前/之上。
- 按下
Trim
按钮,除了最近的图以外,所有图都将从用户界面中完全删除。
library(shiny)
ui <- fluidPage(
actionButton("trim_btn","Trim"),actionButton("run_btn","Run")
)
someplot <- function(nm) {
rand <- sample(nrow(mtcars),size = 1)
plot(disp ~ mpg,data = mtcars,main = paste(nm,"-",rownames(mtcars)[rand]),pch = 16,cex = 1)
points(disp ~ mpg,data = mtcars[rand,drop=FALSE],cex = 2,col = "red")
}
server <- function(input,output,session) {
idcount <- reactiveVal(0)
observeEvent(input$run_btn,{
thisid <- idcount() + 1
idcount(thisid)
thisid <- paste0("plot",thisid)
insertUI(selector = "#run_btn",where = "afterEnd",ui = plotOutput(thisid))
output[[thisid]] <- renderPlot({ someplot(thisid) })
})
observeEvent(input$trim_btn,{
curid <- idcount() - 1
if (curid > 0) {
selectors <- paste0("#plot",seq_len(curid))
# this could be improved to only remove existing selectors
for (sel in selectors) removeUI(selector = sel)
}
})
}
# # Run the application
shinyApp(ui = ui,server = server)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。