如何将导入的数据应用和过滤到 FlaxDashBoard 应用程序(ver.2)中?

How to applying and filtering imported data into the FlaxDashBoard app (ver.2)?

战友们下午好。 我确定没有人帮助过我,tk。我刚刚asked the question之前不太正确。 我正在尝试创建一个 FlexDashcoard 应用程序。要了解该程序的工作原理,您需要我准备的 sample data files。对于文件中的俄语字符,我提前表示歉意,它们是“按原样”呈现给您的。

这是我的代码:

---
title: "AFEA of Russian enterprises"
output: 
  flexdashboard::flex_dashboard:
    storyboard: true
    orientation: rows
    vertical_layout: fill
    theme: simplex
runtime: shiny
---

```{r GlobalOptions}
options(knitr.duplicate.label = 'allow')
```

```{r setup, include=FALSE, echo=FALSE, message=FALSE}
### Library connection module  ###
library("flexdashboard")
library("dygraphs")
library("shiny")
library("shinyFiles")
#options(shiny.trace=TRUE)
library("DT")
library("ggplot2")
library("dplyr")
library("here")
library("data.table")
library("plyr")
### ----------------------------- ###
```

Sidebar {.sidebar}
-------------------------------------
```{r}
roots <- c('C' = 'C:/', 'D' = 'D:/', '//' = '\\ns\Public\Power BI')
rv <- reactiveValues(txt_file  = FALSE)
OKVEDselectInputСhoices<- reactiveValues(data  = NULL)

renderUI({
  shinyFilesButton("files_choose", "Select files", "",
                   multiple=TRUE,
                   buttonType = "default",
                   class = NULL,
                   icon = icon("list-alt"),
                   style = "background-image: linear-gradient(#D9230F, #D9230F 6%, #D9230F); 
                            border-color:  #A91B0C;
                            margin-top: 10px;
                            width: 100%;
                            float: left;
                            box-sizing: border-box;",
                    viewtype = "detail"
  )
})
br()
renderUI({
  actionButton(inputId = "apply", 
                         label = "Apply", 
                         icon = icon("play"),
                         style = "background-image:
                                  linear-gradient(#D9230F, #D9230F 6%, #D9230F);
                                  border-color:  #A91B0C;
                                  margin-top: 10px;
                                  margin-bottom: 10px;
                                  width: 100%;
                                  float: left;
                                  box-sizing: border-box;"
  )
})
br()
renderUI({h6(inputId="sideBarText2", "Выбор ОКВЭД(ов):")})
renderUI({
     selectInput("OKVEDlectInput", 
                  label = NULL,
                  choices = OKVEDselectInputСhoices$data,
                  #selected = "Percent White")
                  multiple=TRUE
    )
})
```

```{r}
shinyFileChoose(input, "files_choose", 
                 roots=roots,
                 filetypes=c('csv'))

observeEvent(
  input$apply,{
    if (!is.null(input$files_choose))
      {
        myInputFile <- parseFilePaths(roots,input$files_choose)$datapath
        
        all.files <- myInputFile
        print(all.files)
        a.vector <- grep("data\-\d+\-structure\-",  all.files, ignore.case = TRUE)
        print(a.vector)
        all.files <- all.files[a.vector]
        all.files<- sort(all.files)
        
        n <- length(all.files)
        print(n)
        data = vector('list', n)
        
        if (n>0) {
          for (i in 2:(n+1)) {
            #print(paste("Вот такой файл:" , all.files[i-1]))
            data[i-1] <- lapply(all.files[i-1],
                              fread,
                              showProgress = TRUE,
                              sep = ";",
                              quote = "",
                              header = FALSE,
                              stringsAsFactors=TRUE,
                              select = c(1:124))
          }
        }
    }
    table <- rbindlist(data)
    UN <- unique(table[[5]])
    UN <-  sort(UN)
    OKVEDselectInputСhoices$data <- UN
    rv$txt_file <- table
    #View(rv$txt_file)
  }
)
```

### Basic information

------------------------------------------------------------------------
```{r}
  #View(rv$txt_file)
```

Some commentary about Frame 1.

### Secondary information

------------------------------------------------------------------------

Some commentary about Frame 2.

You can download the finished version of the code

我的应用程序首先创建一个界面,允许用户select 导入一个(或多个)文件,但具有特定的名称,并将这些数据加载到应用程序中。

以后,我想在全局变量rv$txt_file中包含的这个数据的基础上进行构建,向table输出信息,构建图表,并使用select输入 selection.

但这里有一个奇怪的问题,当我尝试调用 ### Basic information block 中的数据时,我失败了!看不懂,因为变量是全局的...

求助!

不幸的是,没有人帮助我,在花了很多时间之后,我设法解决了这个问题。我真诚地希望有一天有人会发现它有用。

我的第一个错误是使用 observeEvent。如果您参考the official website上的描述,您可以阅读以下信息:

"只要你想执行一个动作来响应一个事件,就使用 observeEvent。(请注意,“重新计算一个值”通常不被视为执行一个动作——请参阅 eventReactive。)第一个参数是你要响应的事件,第二个参数是一个函数,只要事件发生就应该调用它。

使用 eventReactive 创建一个计算值,该值仅响应事件而更新。这就像一个普通的反应式表达式,只是它忽略了所有来自其反应式依赖项的常见失效;它仅在响应给定事件时失效。"

因此,在我的代码中,我需要用 rv_result <- eventReactive (input $ apply, { 替换 observeEvent (input $ dir_choose, {。您还需要在此函数末尾对最终结果进行赋值:rv_result <- rv$txt_file

在块### Basic information中,可以调用一个函数并将结果赋给一个变量:dataset <- reactive({rv_result()})。这是问题第一部分的解决方案,当导入值后,可以对其进行操作。

问题的第二部分是如何使用selectInput来控制带数据的输出table。

一切看起来都很复杂,但最重要的是 selectInput 在选择元素后表示一个值列表,您可以检查和比较 2 个列表。因此,操作 table 的代码如下所示:

renderDT(fillContainer = TRUE,{
      data <- dataset()
      print(class(data))
      if (is.null(input$OKVEDlectInput)) {
        data <- dataset()
      }
      else{
        d1 <- as.list(input$OKVEDlectInput)
        d2 <- as.list(as.vector(data$V5))
        result <- which(!is.na(f(d2, d1,0,0)))
        result <- as.vector(result)
        data <- data[result,]
      }
})

f 函数比较 2 个列表和 returns 要打印的行号:

f <- function(verlist, list_for_ver, resulttyp=0,delna=1) {  
  listforreturn <- vector(mode = 'list', length=0)
  if ((class(verlist)=='list') && (class(list_for_ver)=='list')){
    if (delna==1){
      listforreturn <- as.vector(na.omit(match(verlist,list_for_ver)))
    }
    else{
      listforreturn <- as.vector(match(verlist,list_for_ver))
    }
    
    if (resulttyp==0){
      listforreturn <- as.list(listforreturn)
    }
    else{
      listforreturn<- as.list(list_for_ver[listforreturn])
    }
  }
  return(listforreturn)
}

一切都按要求进行。

完整代码如下:

---
title: "AFEA of Russian enterprises"
output: 
  flexdashboard::flex_dashboard:
    storyboard: true
    orientation: rows
    vertical_layout: fill
    theme: simplex
runtime: shiny
---

```{r GlobalOptions}
options(knitr.duplicate.label = 'allow')
rv <- reactiveValues(txt_file  = FALSE)
OKVEDselectInputChoices<- reactiveValues(data  = NULL)
```

```{r setup, include=FALSE, echo=FALSE, message=FALSE}
### Library connection module  ###
library("flexdashboard")
library("dygraphs")
library("shiny")
library("shinyFiles")
#options(shiny.trace=TRUE)
library("DT")
library("ggplot2")
library("dplyr")
library("here")
library("data.table")
library("plyr")
### ----------------------------- ###
```

Sidebar {.sidebar}
-------------------------------------
```{r}
roots <- c('C' = 'C:/', 'D' = 'D:/', '//' = '\\ns\Public\Power BI')

renderUI({
  shinyFilesButton("files_choose", "Select files", "",
                   multiple=TRUE,
                   buttonType = "default",
                   class = NULL,
                   icon = icon("list-alt"),
                   style = "background-image: linear-gradient(#D9230F, #D9230F 6%, #D9230F); 
                            border-color:  #A91B0C;
                            margin-top: 10px;
                            width: 100%;
                            float: left;
                            box-sizing: border-box;",
                    viewtype = "detail"
  )
})
br()
renderUI({
  actionButton(inputId = "apply", 
                         label = "Apply", 
                         icon = icon("play"),
                         style = "background-image:
                                  linear-gradient(#D9230F, #D9230F 6%, #D9230F);
                                  border-color:  #A91B0C;
                                  margin-top: 10px;
                                  margin-bottom: 10px;
                                  width: 100%;
                                  float: left;
                                  box-sizing: border-box;"
  )
})
br()
renderUI({h6(inputId="sideBarText2", "Выбор ОКВЭД(ов):")})
renderUI({
     selectInput("OKVEDlectInput", 
                  label = NULL,
                  choices = OKVEDselectInputChoices$data,
                  #selected = "Percent White")
                  multiple=TRUE
    )
})
```

```{r}
shinyFileChoose(input, "files_choose", 
                 roots=roots,
                 filetypes=c('csv'))

rv_result <- eventReactive(
  input$apply,{
    if (!is.null(input$files_choose))
      {
        myInputFile <- parseFilePaths(roots,input$files_choose)$datapath
        
        all.files <- myInputFile
        print(all.files)
        a.vector <- grep("data\-\d+\-structure\-",  all.files, ignore.case = TRUE)
        print(a.vector)
        all.files <- all.files[a.vector]
        all.files<- sort(all.files)
        
        n <- length(all.files)
        print(n)
        data = vector('list', n)
        
        if (n>0) {
          for (i in 2:(n+1)) {
            #print(paste("Вот такой файл:" , all.files[i-1]))
            data[i-1] <- lapply(all.files[i-1],
                              fread,
                              showProgress = TRUE,
                              sep = ";",
                              quote = "",
                              header = FALSE,
                              stringsAsFactors=TRUE,
                              select = c(1:124))
          }
        }
    }
    table <- rbindlist(data)
    UN <- unique(table[[5]])
    UN <-  sort(UN)
    OKVEDselectInputChoices$data <- UN
    rv$txt_file <- table
    rv_result <- rv$txt_file
    #View(rv$txt_file)
  }
)

```

### Basic information

```{r}

#renderTable({
#      dataset <- rv_result()
#      dataset
#})

f <- function(verlist, list_for_ver, resulttyp=0,delna=1) {
  # verlist - массив, который требуется проверить на совпадение с элементами второго массива
  # list_for_ver - проверочный массив, т.е. тот, с которым сравнимается
  # resulttyp (0 - выводятся номера элементов list_for_ver, которые найдены);
  #           (1 - выводятся найденные значения)
  # delna -   (0 -если элемент не найде, то он не показывается)
  #           (1 -если элемент не найде, то указывается NA)
  listforreturn <- vector(mode = 'list', length=0)
  if ((class(verlist)=='list') && (class(list_for_ver)=='list')){
    if (delna==1){
      listforreturn <- as.vector(na.omit(match(verlist,list_for_ver)))
    }
    else{
      listforreturn <- as.vector(match(verlist,list_for_ver))
    }
    
    if (resulttyp==0){
      listforreturn <- as.list(listforreturn)
    }
    else{
      listforreturn<- as.list(list_for_ver[listforreturn])
    }
  }
  return(listforreturn)
}


dataset <- reactive({rv_result()})

renderDT(fillContainer = TRUE,{
      data <- dataset()
      print(class(data))
      if (is.null(input$OKVEDlectInput)) {
        data <- dataset()
      }
      else{
        d1 <- as.list(input$OKVEDlectInput)
        d2 <- as.list(as.vector(data$V5))
        result <- which(!is.na(f(d2, d1,0,0)))
        result <- as.vector(result)
        data <- data[result,]
      }
})

```




### Secondary information


Some commentary about Frame 2.