0

I would like to read many .txt files, ignoring the first line and just getting the fifth column. After that, merge all these columns extracted into a data.frame.

I made these with a for loop, building a lot of variables with assign() and then getting all with mget(ls()).

Is there any faster way to do this?

Here are three of these files: we.tl/t-JcVsfiUPLv

Bryan Souza
  • 497
  • 2
  • 10

1 Answers1

1

assign should usually be avoided and in this case we don't need to create these objects in global environment. Try using lapply.

#List all text files in the working directory
filenames <- list.files(pattern = '\\.txt$')
#Read every text file with header, skipping the 1st row. 
#Keep only the 5th column after reading the data. 
result <- lapply(filenames, function(x) read.table(x,skip = 1,header = TRUE)[,5])
result
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213