Michael Michael - 3 months ago 10
R Question

Reading value from a .txt file and writing it into output file

I am trying to read files from a folder, count them and then use for loop with length to go through each file, use

cat
function and for first file, put output in output.txt to be like:


  • file1 : cat output

  • file2 : cat output



My code looks like:

entry = list.files(path = "//Users//michael/Desktop//test_folder", full.names = TRUE, recursive = TRUE)
output = list.files(path = "//Users//michael/Desktop//list.txt", full.names = TRUE, recursive = TRUE)
len = length(entry)
for(i in 1){
cat(entry,file="//Users//michael/Desktop//list.txt", sep="\t", append=TRUE)
cat("\n",file="//Users//michael/Desktop//list.txt", append=TRUE)
}


I have also tried with
for(i in 1:len)
but that would just make this x3 longer because it does it for every iteration of 'i'.

My test_folder looks like:


  • file 1.txt with the values (John, Michael, Fabian ) each one in a new line (\n)

  • file 2.txt has similar values



To summarize:

I am trying to load my test_folder, count number of files (in my case 2), go through each file in for loop and
cat
them so I can see what's inside and then print values inside my list.txt (output) in a format like:


  • file1: cat output

  • file2: cat output



Where is my mistake and how would output/altered code look like in order to make this work?

Answer

Okay, if I understand you correctly, you'd like to open several .txt files from a single directory and then concatenate their contents. I recommend using list.files (like you already are) and then lapply and readLines to open those files.

Get the locations of the .txt files. This produces a list with each element of the list being a directory (file location):

dirs <- list.file(path="path/to/input/directory", full.path=TRUE)

Use lapply to iterate over the elements of the list (like your for loop) and open them with the function readLines. This produces a list with the same number of elements as dirs, but this time it contains the contents of the text files:

myfiles <- lapply(dirs, readLines)

Finally, combine these elements of the list (each containing the contents of one text file) into one object, which you can save as a single text file.

dat <- do.call("rbind", myfiles) # note rbind might need to be replaced with "c" depending on the contents of the .txt files

Sorry if I am missing something or misunderstood. Please comment and I will adapt accordingly.

Comments