Reading multiple files into multiple data frames
In d:\folder, I have many Stata files, such as data_aa_1.dta, data_aa_2.dta, data_aa_3.dta data_bb_1.dta, data_bb_2.dta, data_bb_3.dta, data_cc_1.dta.... I want to convert those files and get as many data frames as the dta files in R. So, I believe I have to loop over c("aa", "bb", "cc") and c(1:3). I tried something like the following:
library(foreign)
for(i in c("aa","bb","cc"){
for (j in 1:3){
data_[i]_[j] <-read.dta("d:/folder/data_[i]_[j].dta")
}
}
But, that looks wrong -- definitely.
Any help will be appreciated.
Thanks!
Try this,
fl = list.files(pattern = "dta", path = "d:/folder",
full.names = TRUE)
dl = lapply(fl, foreign::read.dta)
names(dl) = tools::file_path_sans_ext(fl)
str(dl)
There is undoubtedly a more elegant solution, however
library(foreign)
for(i in c("aa","bb","cc"){
for (j in 1:3){
obj_name <- paste('data', i, j, sep ='_')
file_name <- file.path('d:/folder',paste(obj_name,'dta', sep ='.'))
input <- read.dta(file_name)
assign(obj_name, value = input)
}
}
EDIT
Avoiding the for
loop, and using @joran's suggestion of list.files
dta_files <- list.files('d:/folder', pattern = '.dta', full.names = T)
lapply(dta_files, function(fname){
input <- read.dta(fname)
obj_name <- tools::file_path_sans_ext(basename(fname))
assign(obj_name, value input, env = .GlobalEnv)})