R Shiny技术问题:如何从DT::renderDataTable获取回调值?
解决Shiny中通过Submit按钮获取DT表格单选按钮选中值的问题
你的问题核心是错误地尝试从output$sel获取值,Shiny的output对象仅用于渲染UI输出,不能直接从中提取用户输入值。正确方式是直接从input对象获取单选按钮的选中值——因为你给单选按钮设置的name是空格' ',对应的输入ID就是input[[' ']]。
修改后的关键代码
在observeEvent(input$submit, {...})中直接读取input[[' ']]即可:
observeEvent(input$submit,{ # 获取选中的单选按钮值 selected_value <- input[[' ']] # 可在此处处理值,比如打印、存入数据框等 print(paste("选中的值是:", selected_value)) data <- data.frame(selected_option = selected_value) print(data) })
完整的修改后代码
library(shiny) library(DT) library(googlesheets4) c1 <-c("Time in free flow (mins)", "Time slowed down by other traffic (mins)", "Percentage of total time spent with other vehicles close behind", "Curviness", "Running costs", "Toll cost") c2 <- c('50','10','25%','Moderate','$12.00','$0.00') c3 <- c('38','5','31%','extreame','$10.50','$3.00') c4 <- c('62','8','19%','Almost straight','$9.00','$0.50') c5 <- c('56','15','12%','Moderate','$13.50','$0.00') t <- cbind(c1,c2,c3,c4,c5) shinyApp( ui = fluidPage( title = 'Radio buttons in a table', DT::dataTableOutput('foo'), textOutput('sel'), actionButton("submit", "submit") ), server = function(input, output, session) { m = matrix( as.character(1:4), nrow = 1, ncol = 4, byrow = TRUE, dimnames = list(' ', LETTERS[1:4]) ) for (i in seq_len(nrow(m))) { m[i, ] = sprintf( '<input type="radio" name="%s" value="%s"/>', ' ', m[i, ] ) } m <- cbind('Choice',m) m<-rbind(t,m) output$foo = DT::renderDataTable( m, escape = FALSE, selection = 'none', server = FALSE, options = list(dom = 't', paging = FALSE, ordering = FALSE), callback = JS("table.rows().every(function(i, tab, row) { var $this = $(this.node()); $this.attr('id', this.data()[0]); $this.addClass('shiny-input-radiogroup'); }); Shiny.unbindAll(table.table().node()); Shiny.bindAll(table.table().node());") ) output$sel = renderPrint({ str(sapply(' ', function(i) input[[i]])) }) observeEvent(input$submit,{ # 获取选中值 selected_val <- input[[' ']] # 示例:打印到控制台 cat("提交的选中值:", selected_val, "\n") # 若需在UI展示结果,可新增输出(可选) # output$submit_result <- renderText(paste("您选中的选项是:", selected_val)) }) })
关键说明
- 单选按钮的
name属性决定了它在input中的ID,你设置的是空格' ',因此用input[[' ']]直接读取。 - 不要从
output对象提取用户输入,output仅用于将server端处理后的内容渲染到UI。 - 在
observeEvent中,可对selected_val做任意处理,比如存入数据框、写入Google Sheets等。
内容的提问来源于stack exchange,提问作者Dou
相关产品推荐
相关产品推荐

