我创建了一个示例应用程序,它将向数据表的每一行添加一个按钮,如果按下该按钮,它将根据该行创建一个绘图。请注意,单击的行也会被记录以供以后使用,并保存在名为的变量中SelectedRow()
。如果您需要更多说明,请告诉我
rm(list = ls())
library(DT)
library(shiny)
library(shinyBS)
library(shinyjs)
library(shinydashboard)
# This function will create the buttons for the datatable, they will be unique
shinyInput <- function(FUN, len, id, ...) {inputs <- character(len)
for (i in seq_len(len)) {
inputs[i] <- as.character(FUN(paste0(id, i), ...))}
inputs
}
ui <- dashboardPage(
dashboardHeader(title = "Simple App"),
dashboardSidebar(
sidebarMenu(id = "tabs",
menuItem("Menu Item 1", tabName = "one", icon = icon("dashboard"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "one",h2("Datatable Modal Popup"),
DT::dataTableOutput('my_table'),uiOutput("popup")
)
)
)
)
server <- function(input, output, session) {
my_data <- reactive({
testdata <- mtcars
as.data.frame(cbind(View = shinyInput(actionButton, nrow(testdata),'button_', label = "View", onclick = 'Shiny.onInputChange(\"select_button\", this.id)' ),testdata))
})
output$my_table <- DT::renderDataTable(my_data(),selection = 'single',options = list(searching = FALSE,pageLength = 10),server = FALSE, escape = FALSE,rownames= FALSE)
# Here I created a reactive to save which row was clicked which can be stored for further analysis
SelectedRow <- eventReactive(input$select_button,{
as.numeric(strsplit(input$select_button, "_")[[1]][2])
})
# This is needed so that the button is clicked once for modal to show, a bug reported here
# https://github.com/ebailey78/shinyBS/issues/57
observeEvent(input$select_button, {
toggleModal(session, "modalExample", "open")
})
output$popup <- renderUI({
print(input$select_button)
bsModal("modalExample", "Sample Plot", "", size = "large",
column(12,renderPlot(plot(rnorm(1:10),type="l",col="red",main = paste0("You selected Row Number: ",SelectedRow())))
)
)
})
}
shinyApp(ui, server)
第 1 步:生成带有按钮的表格
正如你所看到的,有一个按钮叫做View
对于每一行
![enter image description here](https://i.stack.imgur.com/s0APk.jpg)
第 2 步:单击按钮后,将生成绘图
请注意,绘图的标题会根据单击的行而变化
![enter image description here](https://i.stack.imgur.com/BlxMK.jpg)