转换CSV中的DTA文件



我想将几个DTA文件转换为CSV。到目前为止,我的代码是(老实说,我使用了在Stackoverflow上找到的答案...

library(foreign)
setwd("C:UsersVictorFolder") 
for (f in Sys.glob('*.dta')) 
    write.csv(read.dta(f), file = gsub('dta$', 'csv', f))

它有效,但是如果我的文件夹包含子文件夹,它们将被忽略。我的问题是我有11个子文件夹(可能包含子文件夹本身),我想找到一种方法来循环我的文件夹和子文件夹,因为现在我需要为每个子文件夹更改我的工作目录和。

我现在正在使用r,我尝试使用pandas(python),但是转换的质量似乎是有争议的...

谢谢

在R中进行此操作,您只是在list.files中设置recursive = T

实际上,在处理目录时指定递归是一般的 - 它可以与OS中的命令行操作一起使用,包括Linux和Windows,windows和Windows具有rm -rf之类的命令,并适用于R。

中的多个功能

这篇文章有一个很好的例子:

如何通过子文件夹使用R进行迭代并绑定同一ID的CSV文件?

他们的示例(仅在目录/子目录搜索的结果中所做的事情有所不同)是:

 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中设置您的基本目录。

考虑使用base 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中的对应物具有内置方法来读写Stata文件:

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")))

最新更新