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!
>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')