Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

r - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...