gpt4 book ai didi

r - 如何使用数据表函数替换在 R 中呈现的 DT 中的数据

转载 作者:行者123 更新时间:2023-12-04 01:42:25 25 4
gpt4 key购买 nike

我有一个 R shiny带有 DT 的应用程序datatable使用 datatable 渲染功能以设置各种选项。我想用 dataTableProxyreplaceData更新表中的数据,但我能找到的所有示例都假设 DT直接从数据对象呈现,不使用 datatable功能。下面的 reprex 显示了我想做的事情,但是 replaceData在这种模式下不起作用。我该怎么做呢?谢谢。


# based on
# https://community.rstudio.com/t/reorder-data-table-with-seleceted-rows-first/4254

library(shiny)
library(DT)

ui = fluidPage(
actionButton("button1", "Randomize"),
fluidRow(
column(6,
h4("Works"),
DT::dataTableOutput('table1', width="90%")),
column(6,
h4("Doesn't Work"),
DT::dataTableOutput('table2', width="90%"))
)
)

server = function(input, output, session) {

my <- reactiveValues(data = iris)

output$table1 <- DT::renderDataTable(isolate(my$data))

output$table2 <- DT::renderDataTable({
DT::datatable(isolate(my$data),
options = list(lengthChange=FALSE, ordering=FALSE, searching=FALSE,
columnDefs=list(list(className='dt-center', targets="_all")),
stateSave=TRUE, info=FALSE),
class = "nowrap cell-border hover stripe",
rownames = FALSE,
editable = FALSE
) %>%
DT::formatStyle('Sepal.Width', `text-align`="center")
})

observeEvent(input$button1, {

# calculate new row order
row_order <- sample(1:nrow(my$data))
my$data <- my$data[row_order, ]

proxy1 <- DT::dataTableProxy('table1')
DT::replaceData(proxy1, my$data)
proxy2 <- DT::dataTableProxy('table2')
DT::replaceData(proxy2, my$data)

})

}

shinyApp(ui, server)

最佳答案

更新:很奇怪,删除 rownames = FALSE使这一切成为可能。我不确定为什么,但行名可能对替换数据至关重要。

# based on 
# https://community.rstudio.com/t/reorder-data-table-with-seleceted-rows-first/4254

library(shiny)
library(DT)

ui = fluidPage(
actionButton("button1", "Randomize"),
fluidRow(
column(6,
h4("Works"),
DT::dataTableOutput('table1', width="90%")),
column(6,
h4("Doesn't Work"),
DT::dataTableOutput('table2', width="90%"))
)
)

server = function(input, output, session) {

my <- reactiveValues(data = iris)

output$table1 <- DT::renderDataTable(isolate(my$data))

output$table2 <- DT::renderDataTable({
DT::datatable(isolate(my$data),
options = list(lengthChange=FALSE, ordering=FALSE, searching=FALSE,
columnDefs=list(list(className='dt-center', targets="_all")),
stateSave=TRUE, info=FALSE),
class = "nowrap cell-border hover stripe",
# rownames = FALSE,
editable = FALSE
) %>%
DT::formatStyle('Sepal.Width', `text-align`="center")
})

observeEvent(input$button1, {

# calculate new row order
row_order <- sample(1:nrow(my$data))
my$data <- my$data[row_order, ]

proxy1 <- DT::dataTableProxy('table1')
DT::replaceData(proxy1, my$data)
proxy2 <- DT::dataTableProxy('table2')
DT::replaceData(proxy2, my$data)

})

}

shinyApp(ui, server)

关于r - 如何使用数据表函数替换在 R 中呈现的 DT 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56879672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com