[英]Unique row DT::renderDataTable() in Shiny R trigger query
嗨,我是嶄新的,具有數據響應性。 我希望您能提供幫助,我將一個查詢嵌入到一個觀察函數中,該函數響應DT :: renderDataTable()中唯一行選擇的輸入。 當用戶選擇行時,矢量遞增,例如,選擇了第1行,然后選擇了第8行,則返回的矢量為[1] 18。然后,這些值通過子集例程輸入到查詢中,以獲取id作為文本字符串。 即與ID“ ch10”有關的字符8。 postgres查詢一次只能取1個值,但是我想在將所有選項都繪制在一起之前將所有選擇rbind放入數據幀中。 我可以使用for循環來執行此操作,但這並不是非常有效且耗時。 同樣,每次迭代並更新繪圖時,都會再次遍歷所有矢量,然后重新繪圖所有選擇以及新添加的內容。 我需要做的是將新的向量行添加到數據框中,並驗證ID是否已存在於數據框中,拒絕是否已存在,或者添加它們是否已存在然后進行繪圖,這可以在觀察函數中完成嗎? 任何幫助將不勝感激。 這是來自觀察功能的主要代碼:
ids <- input$x3_rows_selected
dat1 = isolate(paste0(dat[ids, , drop = FALSE][[1]], sep = ""))
if (dat1[1]=='')
return(NULL)
result = list()
for (i in 1:length(dat1)){
dat2 = dbGetQuery(con2, paste0("select * from getsession('",dat1[i],"'), sep=""))
dat2$sessionid = dat1[i]
result[[i]] = dat2
}
big_data = do.call(rbind, result)
這是一個潛在的解決方案,可讓您步入正軌。 我使用行選擇的selectizeInput
和一個簡單的子集語句(而不是sql查詢) selectizeInput
進行了略微的簡化,但是思想/實現非常相似。
基本上,您可以添加兩個reactiveVals
; 一個用於所選行,另一個用於表。 然后,您可以創建一個observeEvent
來在輸入更改時進行調整。 如您在此解決方案中所看到的,選擇行時僅將它們提取一次,並且如果進行了新選擇,則observeEvent
將添加新行。 這使我們不必經常通過for循環。
library(shiny)
mtcars$id = seq(nrow(mtcars)) # add unique id
ui <- fluidPage(
selectizeInput('input1','Select rows:',choices=seq(nrow(mtcars)),multiple=T),
tableOutput('result')
)
server <- function(input,output)
{
# initiate table with right column headers
my_table <- reactiveVal(mtcars[0,])
# initiate out selection
selection <- reactiveVal()
observeEvent(input$input1, ignoreNULL = F,
{
# if any from input1 not yet in our selection
if(any(!input$input1 %in% selection()))
{
to_add = input$input1[!input$input1 %in% selection()] # which id to add?
selection(c(selection(),to_add)) # update the reactiveVal
df_to_add = mtcars[mtcars$id==to_add,] # your sql query here
my_table(rbind(my_table(),df_to_add)) # update the table reactiveVal
}
else
{
# if there are rows selected that the user has deselected ...
if(any(!selection() %in% input$input1 ))
{
selection(input$input1) # set selection to the user input
# remove the deselected rows from the table
my_table(my_table()[my_table()$id %in% input$input1,] )
}
}
})
output$result <- renderTable({my_table()})
}
shinyApp(ui,server)
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.