Brockagh
Brockagh

Reputation: 31

read multiple files into r, no column names

I have a number of .txt files, with the data comma separated. There are no headers. Each contains the same information, but by different years: the name, the gender and the number of names.

I can read them all in in one rbind okay, but I lose the year information - the year is contained only in the file name... y1920.txt, y1995.txt, y2002.txt and so on.

I am very new to R.

To rbind them, I used do.call(file, rbind), where file is the list of data.frames.

Upvotes: 1

Views: 414

Answers (1)

Mathew Hall
Mathew Hall

Reputation: 1004

Plyr has a nice workflow for this, assuming your files are all in the current working directory:

library(plyr)
years <- ldply(list.files(pattern="y\\d{4}\\.txt"), 
               function(file){ 
                 data <- read.csv(file, header=F); 
                 data$date <- gsub("y","",gsub("\\.txt","", file)); 
                 data})

If you want to specify your files instead, e.g. files <- c("y1995.txt", "y1996.txt"), you can replace the first argument to ldply (list.files(...)) with files instead.

Upvotes: 2

Related Questions