-2

I have hundreds of .txt files. I want to automate a process to read them all and save them with their respective file name. For example, I want to save them in this order without typing the name of individual files.

mytext1.txt <-read.table("./mytext1.txt", sep = "\t")
mytext2.txt <-read.table("./mytext2.txt", sep = "\t") 

Here is the code I have tried which of course doesn't save the dataframe in a separate object name.

filelist = list.files(pattern = ".*.txt")   
datalist = lapply(filelist, FUN=read.table, header=TRUE, sep = "\t")
MAPK
  • 5,635
  • 4
  • 37
  • 88
  • 1
    Why not name the entries of `datalist` by `filelist`? `names(datalist) <- filelist`. – Mosquite Dec 06 '17 at 21:15
  • This question has been asked several times already, but the dupe target is not good, because the OP of the duped question has stated that he has only 8 files with *different file structures*. – Uwe Dec 06 '17 at 23:45

2 Answers2

0

It looks like you are missing a line:

datafr = do.call("rbind", datalist)

See this post for reference: How do you read in multiple .txt files into R?

stevebroll
  • 175
  • 1
  • 8
  • Thanks, but I want them in a separate dataframe with their respective file names. – MAPK Dec 06 '17 at 21:14
  • My mistake. Instead, see this post: https://stackoverflow.com/questions/5319839/read-multiple-csv-files-into-separate-data-frames. It looks like the assign function is what you're looking for. – stevebroll Dec 06 '17 at 21:17
  • @stevebroll The OP in the linked question is stating that he has just 8 files of *different file structure*. If there is a large number of files having the same structure it's better to store them in a list or `rbindlist()` them, IMHO. – Uwe Dec 06 '17 at 23:39
0

This may not be the best way, but it should do what you want:

read.and.write.table <- function(files){
    for(fn in files){
        input <- read.table(file = fn, header = TRUE, sep = "\t")
        assign(x = fn, value = input, envir = .GlobalEnv)
    }
}

filelist = list.files(pattern = ".*.txt")  
read.and.write.table(filelist)

Will create separate global variables named after your .txt files. Of course you could include some string manipulation to pretty up the names.

MDK
  • 301
  • 3
  • 11
  • 2
    `fortunes::fortune(236)`: *The only people who should use the assign function are those who fully understand why you should never use the assign function. -- Greg Snow R-help (July 2009)* – Uwe Dec 06 '17 at 23:34