我想将几个dta文件转换为csv。 到目前为止,我的代码是(说实话,我使用了我在stackoverflow上找到的答案......)
library(foreign)
setwd("C:\Users\Victor\Folder")
for (f in Sys.glob('*.dta'))
write.csv(read.dta(f), file = gsub('dta$', 'csv', f))
它有效,但如果我的文件夹包含子文件夹,则会被忽略。 我的问题是我有11个子文件夹(可能包含子文件夹)我想找到一种方法来循环我的文件夹和子文件夹,因为现在我需要更改每个子文件夹的工作目录和。
我现在正在使用R,我尝试使用pandas(python),但似乎转换的质量值得商榷......
谢谢
答案 0 :(得分:0)
在R中执行此操作,您只需在recursive = T
中设置list.files
即可。
实际上,在处理目录时指定递归是一种通用 - 它适用于操作系统中的命令行操作,包括Linux和Windows,使用rm -rf
等命令,并适用于R中的多个函数。
这篇文章有一个很好的例子:
How to use R to Iterate through Subfolders and bind CSV files of the same ID?
他们的示例(仅与他们对目录/子目录搜索结果的处理方式不同)是:
lapply(c('1234' ,'1345','1456','1560'),function(x){
sources.files <- list.files(path=TF,
recursive=T,
pattern=paste('*09061*',x,'*.csv',sep='')
,full.names=T)
## You read all files with the id and bind them
dat <- do.call(rbind,lapply(sources.files,read.csv))
### write the file for the
write(dat,paste('agg',x,'.csv',sep='')
}
那么对于你pattern = '.dta'
,只需在path
中设置你的基目录。
答案 1 :(得分:0)
考虑使用基本R list.files(),因为递归参数指定在子目录中搜索。您还需要设置 full.names 以返回文件引用的绝对路径。
因此,设置模式以查找.dta
扩展名(即Stata数据集),然后运行读入和写出功能:
import foreign
statafiles <- list.files("C:\\Users\\Victor\\Folder", pattern="\\.dta$",
recursive = TRUE, full.names = TRUE)
lapply(statafiles, function(x) {
df <- read.dta(x)
write.csv(df, gsub(".dta", ".csv", x))
})
Python pandas中的对应物,它有read and write stata files的内置方法:
import os
import pandas as pd
for dirpath, subdirs, files in os.walk("C:\\Users\\Victor\\Folder"):
for f in files:
if f.endswith(".dta"):
df = pd.read_stata(os.path.join(dirpath, f))
df.to_csv(os.path.join(dirpath, f.replace(".dta", ".csv")))