Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add file names in a column when using fread

I have several .txt files that I am importing with the following code:

files = list.files(pattern="*.txt")%>% 
     map_df(~fread(.))

Each file has several rows and columns, and I want to add an id row with the file name. So if the files were called A-ML201.txt and A-YH248, etc., I would get the following. The file names need to repeat since each file has multiple rows:

ID         col1    col2 
A-ML201     2       67
A-ML201     4       29
A-ML201     1       90
A-YH248     23      2
A-YH248     12      17
A-YH248     8       57

I have tried a few solutions from this thread: How to import multiple .csv files at once?. But keep getting errors, maybe because they are .txt files? I tried replacing read.csv with read.table. I am new to this kind of thing so any help is greatly apppreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We could pass a named vector and then use .id

library(purrr)
library(dplyr)
library(stringr)
library(data.table)
files <- list.files(path = "path/to/your/folder", 
    pattern="\\.txt", full.names = TRUE)
names(files) <- str_remove(basename(files), "\\.txt")
map_dfr(files, fread, .id = 'ID')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading