Reputation: 11
I need to read multiple Txt file in R to create a unique dataset and export it on Excel. this is what I used
BHCFYYMM <- read.table('bhcf1803.txt''bhcf1806.txt''bhcf1809.txt''bhcf1812.txt', sep="^", nrows=1300, comment.char="", header=TRUE, quote="", na.strings="--------", as.is=TRUE)
setwd("/Users/marco/Desktop/research/silvio")
getwd()
write.table(BHCFYYMM, file = "HoldingCompanyData.csv", sep = ",")
but i get this error:
Error: unexpected string constant in "BHCFYYMM <- read.table('bhcf1803.txt''bhcf1806.txt'"
Any idea how I can approach this?
Upvotes: 1
Views: 1293
Reputation: 11
Your code likely failed because you can not give read.table()
multiple file paths at once.
You can instead use lapply()
to feed a list of file paths to read.table()
. The tables can then be combined using dplyr::bind_rows()
.
(assuming the other parameters you have provided are correct)
# Load dplyr
# install.packages("dplyr")
library(dplyr)
# It is usually best practice to set your working directory before you do anything else.
setwd("/Users/marco/Desktop/research/silvio")
# Make list of files.
files <- c("bhcf1803.txt", "bhcf1806.txt", "bhcf1809.txt", "bhcf1812.txt")
# Read files into a list of tables.
tables <- lapply(X = files, FUN = read.table, sep = "^", nrows = 1300, comment.char = "", header = TRUE, quote = "", na.strings = "--------", as.is = TRUE)
# Bind tables together into a single table.
BHCFYYMM <- bind_rows(tables)
# Write table to a new file.
write.table(BHCFYYMM, file = "HoldingCompanyData.csv", sep = ",")
Upvotes: 1
Reputation: 36
I don't know what is in a text file but this is what I generally do if I want to import multiple files and bind them
#set working directory
setwd("C:/xxxx/xxxx/Desktop/DUMP/")
#select the pattern of the file extension
files <- list.files(pattern=".txt")
#read all the files and bind the rows
tbl<-lapply(files, read.table) %>% bind_rows()
Upvotes: 0