Home > Software design >  Importing several txt files in R
Importing several txt files in R

Time:02-22

I would like to import several ".txt" file in R and add a new "ID" column with the file name in it. I found something like that that works to import all the txt files but I don't have my "ID" column.

listfile <- list.files("C:/Users/........",pattern = "txt",full.names = T, recursive = TRUE)

for (i in 1:length(listfile)){
  if(i==1){
    assign(paste0("Data"), read.table(listfile[i],header = TRUE, sep = ",", skipNul = TRUE))
  }
}

rm(list = ls(pattern = "list. ?"))

All the files name have this format: "XXX-M_N6 2021-04-16.txt" with different letter instead of "XXX" and other date as well. Any idea how to do that? Thanks!

CodePudding user response:

library(purrr)


purrr::map_dfr(listfile, 
               ~{cbind(read.table(.x, header = TRUE, sep = ",", skipNul = TRUE),
                       ID = .x)})

CodePudding user response:

Using R base, you can try something like:

path_arqs = dir() # accept that your csvs files are the same
df = do.call(rbind, lapply(path_arqs, read.csv))
  • Related