在Shiny App中使用ends_with在R中动态添加选择列

时间:2018-10-18 13:26:10

标签: r shiny tidyverse shinydashboard shiny-reactivity

使用stackoverflow,我创建了一个闪亮的应用程序,该应用程序上传一个csv文件,然后显示一个数据表。

在选择列dynamically之后,其中某些列的结尾为“ _down ”。

我需要帮助缩短数据框(如下面的代码所示),并按ID列(如果有)删除重复项。

    # install.packages("shiny")
    # install.packages("DT")
    # install.packages("shinycssloaders")
    library(DT)
    library(shiny)
    library(shinycssloaders)

UI代码

    ##Creating the UI as a fluidPage,
    ##fluidPage allows scaling components of the browser in realtime to fill all available broswer width
    ##This is standard
    ui <- fluidPage(

      # Title of app
      titlePanel("Upload file to table"),


        # Main panel for displaying outputs
        mainPanel(

          #fileInput with acceptance of text/csv and more
          fileInput('file', 'Choose file to upload',
                    accept = c(
                      'text/csv',
                      'text/comma-separated-values',
                      'text/tab-separated-values',
                      'text/plain',
                      '.csv',
                      '.tsv',
                      '.html'
                    )),


          # Output: datatable
          DT::dataTableOutput("data_as_table")%>%withSpinner(),

          #Download button
          downloadButton("downloadData", "Download")

        )
    )

服务器代码

创建服务器

    server <- function(input, output) {


      #Data is a reactive element meaning it will update when the reactive input inside it change
      #Data will update when input$file changes
      #input$file is the uploaded file (se fileInput in ui)
      data <-reactive({

        #Store input$file as inFile 
        inFile <- input$file

        #if its empty return nothing
        if (is.null(inFile))
          return(NULL)

        #read in the file as a csv, with headers, comma seperated
        dd = read.csv(inFile$datapath, header = T,
                 sep = ",")
        dd  = as.data.frame(dd)

        #Shortening dataframe 
        #dd= dd[apply(dd[, endsWith(colnames(dd), "_down")], 1, function(x) any(x == "TRUE")), ]


        #Remove duplicates by ID column, and show unique
        #xxx
        return(dd)
      })



    #Make the output data_as_table a datatable containing the reactive element data
     output$data_as_table<-DT::renderDataTable({
       data()
     })


     # Downloadable csv of reactive data() object
     output$downloadData <- downloadHandler(
       filename = function() {
         paste("Download", Sys.date(), ".csv", sep = "")
       },
       content = function(file) {
         write.csv(data(), file, row.names = FALSE)
       }
     )
    }

    #Launch shiny app
    shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

您可以使用dplyr::distinct删除重复项。它只会保留ID的第一个实例,并删除其他实例。在您的情况下,将其添加到return(dd)反应式的data之前-

if("ID" %in% names(dd)) {
    dd <- dplyr::distinct(dd, ID, .keep_all = T)
}