简体   繁体   English

将过滤后的 DT::datatable 保存到新的数据帧 R 闪亮

[英]Save filtered DT::datatable into a new dataframe R shiny

Let's say that I have a shiny app displaying a data table like the following:假设我有一个闪亮的应用程序,显示如下所示的数据表:

library(shiny)
library(tidyverse)
library(datasets)
library(DT)

data<- as.data.frame(USArrests)
#data<- cbind(state = rownames(data), data)
ui <- fluidPage(
    dataTableOutput("preview")
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$preview<- renderDataTable(
        datatable(data, options = list(searching = T, pageLength = 10, lengthMenu = c(5,10,15, 20), scrollY = "600px", scrollX = T ))
    )
    
}

# Run the application 
shinyApp(ui = ui, server = server)

Let's say I then type in "Iowa" into the search box.假设我然后在搜索框中输入“爱荷华州”。 I would like to save that filtered datatable into a seperate dataframe within the app.我想将过滤后的数据表保存到应用程序内的单独数据框中。 I would like it to be dynamic as well so if I typed "Kentucky", it would save Kentucky's filtered data into the dataframe instead.我也希望它是动态的,所以如果我输入“肯塔基州”,它会将肯塔基州的过滤数据保存到数据框中。 Is there a way to do this?有没有办法做到这一点? NOTE: this is a DT datatable注意:这是一个 DT 数据表

Maybe this type of solution.也许这种类型的解决方案。 It is possible to add further conditions like checking the first letter in upper case, but the main idea is to check each column and search for the pattern entered inside the datatable searchbox.它可以附加额外的条件一样检查大写的第一个字母,但主要的想法是检查每一列和搜索内输入图形datatable搜索框。 This may or may not result in more than one dataset to print (depending if the string is partially matched in multiple columns (this is also solvable with rbind function.这可能会也可能不会导致打印多个数据集(取决于字符串是否在多列中部分匹配(这也可以使用rbind函数解决。

code:代码:

library(shiny)
library(tidyverse)
library(datasets)
library(DT)
data <- as.data.frame(USArrests)
data <- cbind(state = rownames(data), data)
ui <- fluidPage(
  dataTableOutput("preview"),
  tableOutput('filtered_df')
)

# Define server logic required to draw a histogram
server <- function(input, output) {
  
  df <- reactiveValues()
  
  output$preview<- renderDataTable(
    datatable(data, options = list(searching = T, pageLength = 10, lengthMenu = c(5,10,15, 20), scrollY = "600px", scrollX = T ))
  )
 
  observeEvent(input$preview_search, {
   searched_string <- map(data, ~str_subset(.x, input$preview_search)) %>% discard(~length(.x) == 0)  
   
   df$filtered <- syms(names(data)) %>%
                   map(~ filter(data, !!.x %in% searched_string)) %>%
                   discard(~ nrow(.x) == 0)
   
   
   
  })
  
  output$filtered_df <- renderTable({df$filtered})
  
}

# Run the application 
shinyApp(ui = ui, server = server)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM