Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a data frame with the contents of multiple txt files

Tags:

r

I'm new to R programming and am having difficulties trying to create one data frame from a number of text files. I have a directory containing over 100 text files. Each of the files have a different file name but the contents are of a similar format e.g. 3 columns (name, age,gender). I want to load each of the text files into R and merge them into 1 data frame.

So far I have:

txt_files = list.files(path='names/', pattern="*.txt");
do.call("rbind", lapply(txt_files, as.data.frame))

This has created a list of the file names but not the contents of the files. I'm able to read in the content of one file and create a data frame but I can't seem to do it for multiple files at once. If anyone could offer any help I'd really appreciate it as I'm completely stuck!

Thanks in advance!

like image 536
Karen Avatar asked Oct 08 '16 20:10

Karen


1 Answers

I think you might want something like this:

# Put in your actual path where the text files are saved
mypath = "C:/Users/Dave/Desktop"
setwd(mypath)

# Create list of text files
txt_files_ls = list.files(path=mypath, pattern="*.txt") 
# Read the files in, assuming comma separator
txt_files_df <- lapply(txt_files_ls, function(x) {read.table(file = x, header = T, sep =",")})
# Combine them
combined_df <- do.call("rbind", lapply(txt_files_df, as.data.frame)) 

At least that worked for me when I created a couple of sample text files. Hope that helps.

like image 178
DaveM Avatar answered Nov 09 '22 18:11

DaveM