Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include .csv filename when reading data into r using list.files

Tags:

r

csv

dplyr

I'm aggregating a bunch of CSV files in R, which I have done successfully using the following code (found here):

  Tbl <- list.files(path = "./Data/CSVs/",
         pattern="*.csv", 
         full.names = T) %>% 
   map_df(~read_csv(., col_types = cols(.default = "c"))) 

I want to include the .csv filename (ideally without the file extension) as a column in Tbl. I found a solution using plyr, but I want to stick with dplyr as plyr causes glitches further down my code.

Is there any way I can add something to the above code that will tell R to include the file name in Tbl$filename?

Many thanks!

like image 290
Catherine Laing Avatar asked Jun 09 '17 16:06

Catherine Laing


People also ask

How do I read a csv file in RStudio?

In RStudio, click on the Workspace tab, and then on “Import Dataset” -> “From text file”. A file browser will open up, locate the . csv file and click Open. You'll see a dialog that gives you a few options on the import.

Which function is used to read a csv file in R?

csv() Function. read. csv() function in R Language is used to read “comma separated value” files. It imports data in the form of a data frame.


Video Answer


1 Answers

Here's my solution. Let me know if this helps.

Tbl <- list.files(path = "./Data/CSVs/",
         pattern="*.csv", 
         full.names = T) %>% 
   map_df(function(x) read_csv(x, col_types = cols(.default = "c")) %>% mutate(filename=gsub(".csv","",basename(x)))) 
like image 54
A Gore Avatar answered Oct 05 '22 03:10

A Gore