1

I want to upload multiple *.csv files, rbind them and create new column named Filename with original csv filenames.

With basename() function I am only apply to get temp file name and not the original filename.

input$datafile$name gets the original file name but I am not sure how to mutate new column from this name.

Below is my code for reference.

library(shiny) library(data.table) library(dplyr) options(shiny.maxRequestSize = 10000*1024^2) ui <- shinyUI( fluidPage( titlePanel("Example Read and Merge with new Column for Filename"), sidebarLayout( sidebarPanel( fileInput("datafile", h5("Choose CSV file:"), accept = ".csv",multiple = TRUE)), mainPanel(DT::dataTableOutput("Raw_data_show"), verbatimTextOutput("results"),textOutput("filechosen")) ))) server <- function(session,input, output) { path <- reactiveValues(pth=NULL) observeEvent(input$filechoose,{ path$pth <- file.choose() }) output$filechosen <- renderText({ if(is.null(path$pth)){ return() }else{ dirname(path$pth) } }) rawData <- reactiveValues(site = NULL) observeEvent(input$datafile, { req(input$datafile) rawData$site <- input$datafile$datapath%>% purrr::map_df(~fread(.x)%>%mutate(FileName_2D = basename(.x))) }) output$results = renderPrint({ input$datafile$name print(paste("First File (input$datafile$name)[[1]])",(input$datafile$name)[[1]])) print(paste("2nd File (input$datafile$name)[[2]])",(input$datafile$name)[[2]])) }) output$Raw_data_show <- DT::renderDataTable({ rawData$site }) } shinyApp(ui, server) 

Below is the image of the app so far.

UploadCSV_rbind_createColumn

Appreciate some inputs.

1 Answer 1

2

You can use input$datafile$datapath to read the file and input$datafile$name to add a new column with the file name. Use map2_df to pass both the values together and combine into one dataset.

library(shiny) library(tidyverse) library(data.table) ui <- shinyUI( fluidPage( titlePanel("Example Read and Merge with new Column for Filename"), sidebarLayout( sidebarPanel( fileInput("datafile", h5("Choose CSV file:"), accept = ".csv",multiple = TRUE)), mainPanel(DT::dataTableOutput("Raw_data_show"), verbatimTextOutput("results"),textOutput("filechosen")) ))) server <- function(session,input, output) { path <- reactiveValues(pth=NULL) observeEvent(input$filechoose,{ path$pth <- file.choose() }) output$filechosen <- renderText({ if(is.null(path$pth)){ return() }else{ dirname(path$pth) } }) rawData <- reactiveValues(site = NULL) observeEvent(input$datafile, { req(input$datafile) rawData$site <- map2_df(input$datafile$name, input$datafile$datapath, ~fread(.y)%>% mutate(FileName_2D = .x)) }) output$Raw_data_show <- DT::renderDataTable({ rawData$site }) } shinyApp(ui, server) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.