我想把几个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),但似乎转换的质量是有争议的……
谢谢
发布于 2016-06-30 00:57:33
在R中,您只需在list.files中设置recursive = T即可。
实际上,在处理目录时指定递归是一种通用的方式--它适用于操作系统(包括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='')
}所以对你来说,只需在path中设置你的基本目录就可以了。
发布于 2016-06-30 11:18:07
考虑使用基数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")))https://stackoverflow.com/questions/38105378
复制相似问题