【问题标题】:Convert dta files in csv在csv中转换数据文件
【发布时间】:2016-06-29 16:32:51
【问题描述】:

我想将几个 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),但似乎转换的质量值得商榷......

谢谢

【问题讨论】:

    标签: python r csv


    【解决方案1】:

    在 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='')
       }
    

    所以对于你pattern = '.dta',只需将你的基本目录设置在path

    【讨论】:

      【解决方案2】:

      考虑使用基本 R 的 list.files() 作为 recursive 参数指定在子目录中搜索。您还希望 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")))
      

      【讨论】:

      • 感谢您的回答。当我尝试您的代码时,出现错误:'错误:“}”中的意外'}''。熊猫也可以阅读 stata 文件吗?我用 python 编写代码,但速度很慢,这就是为什么我使用 R 跳跃它会更快!
      • 看不到为什么您会收到错误所有大括号和括号都正确关闭。您是否突出显示了整个 lapply?尝试任一性能。一切都取决于数据量、文件数量等。对于 csv 转换,我无法想象它们会有很大的不同,甚至它们会相当慢
      猜你喜欢
      • 2021-09-16
      • 2019-09-11
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多