Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read all files in one directory into R at once? [duplicate]

Tags:

r

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=",")
like image 343
user2806363 Avatar asked Dec 08 '22 10:12

user2806363


1 Answers

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.

like image 161
tonytonov Avatar answered May 22 '23 00:05

tonytonov