I have an app that inserts plots using the insertUI function. I am now trying to do the following:
When the user inserts a plot using the action button, another action button next to the plot should appear that has the functionality of removing that specific plot when clicked.
I believe that I am pretty close to the solution in the example: The buttons get inserted with the plots, however, only the first inserted button works (for all elements). How can I connect a button with the respective plots?
Any help would be highly appreciated
Here is a minimal expample:
library(shiny)
library(shinydashboard)
# Dummy data
a<-(letters)
b<-rnorm(length(letters), 4,2)
c<-rnorm(length(letters), 10,15)
d<-c(1:10,20:30,45:49)
data<-data.frame(a,b,c,d)
names(data)<-c("name","v1","v2","v3")
# UI
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
actionButton("add", "Add"),
radioButtons("add_elements","", c("Element1", "Element2"))
),
dashboardBody(
fluidRow( tags$div(id="placeholder")
)
))
# Server Logic
server <- function(input, output, session) {
# Initialize empty vector
inserted<- c()
# Observer
observeEvent(input$add, {
id_add <- paste0(input$add, input$add_elements)
insertUI(selector = '#placeholder', where = "afterEnd",
ui= switch(input$add_elements,
'Element1'= plotOutput(id_add),
'Element2' = plotOutput(id_add))
)
output[[id_add]] <-
if (input$add_elements == "Element1")
renderPlot({
plot(data[,1],data[,2])
}) else if (input$add_elements == "Element2")
renderPlot({
plot(data[,1],data[,4])
})
inserted <<- c(id_add,inserted)
insertUI(
selector = "#placeholder",
where = "afterEnd",
ui = tags$div(actionButton("remove_button", "Remove"))
)})
## Remove Elements ###
observeEvent(input$remove_button, {
removeUI(
selector = paste0('#', inserted[length(inserted)])
)
inserted <<- inserted[-length(inserted)]
})
}
shinyApp(ui = ui, server = server)