6

I have folder, which contain around 200 .txt files. I want to read all of the files and select second column of each of them and put them in one matrix. (rbind()) is there any command to read all files at once ?

I want to use :

data<-read.table ("", header= T, sep=",")
user2806363
  • 2,513
  • 8
  • 29
  • 48

1 Answers1

17

There are three steps:

  1. Fetch all file names via list.files
  2. Use lapply to read all files in a list
  3. Use do.call to rbind all data into a single data frame or matrix

The code:

nm <- list.files(path="path/to/file")
do.call(rbind, lapply(nm, function(x) read.table(file=x)[, 2]))

Subsetting with [] is arbitrary, this example is for the second columns only.

tonytonov
  • 25,060
  • 16
  • 82
  • 98
  • use data.table::fread() instead of read.table() & data.table::rbindlist() instead of rbind() which is 10 times faster than the rbind(). [https://rstudio-pubs-static.s3.amazonaws.com/406521_7fc7b6c1dc374e9b8860e15a699d8bb0.html](https://rstudio-pubs-static.s3.amazonaws.com/406521_7fc7b6c1dc374e9b8860e15a699d8bb0.html) – Abhishek Agnihotri Apr 01 '21 at 12:44