正确表达循环,将所有.dta文件转换为目录中的.csv

时间:2023-01-14 23:40:04

So I have a single instance of dta to csv conversion, and I need to repeat it for all files in a directory. Great help on SO, but I'm still not quite there. Here's the single instance

所以我有一个dta到csv转换的单个实例,我需要为目录中的所有文件重复它。在SO方面提供了很大的帮助,但我仍然没有那么做。这是单个实例

#Load Foreign Library
library(foreign)

## Set working directory in which dtw files can be found)
setwd("~/Desktop")

## Single File Convert
write.csv(read.dta("example.dta"), file = "example.csv")

From here, I figure I use something like:

从这里,我想我使用的东西:

## Get list of all the files
file_list<-dir(pattern = ".dta$", recursive=F, ignore.case = T)

## Get the number of files
n <- length(file_list)

## Loop through each file
for(i in 1:n) file_list[[i]]

But I'm not sure of the proper syntax, expressions, etc. After reviewing the great solutions below, I'm just confused (not necessarily getting errors) and about to do it manually -- quick tips for an elegant way to go through each file in a directory and convert it?

但是我不确定正确的语法,表达方式等。在回顾下面的优秀解决方案后,我只是感到困惑(不一定是错误)并且即将手动执行 - 快速提示以便通过优雅的方式完成目录中的每个文件并转换它?

Answers reviewed include:

审核的答案包括:

Convert Stata .dta file to CSV without Stata software

将Stata .dta文件转换为CSV而不使用Stata软件

applying R script prepared for single file to multiple files in the directory

将为单个文件准备的R脚本应用于目录中的多个文件

Reading multiple files from a directory, R

从目录中读取多个文件,R

THANKS!!

谢谢!!

Got the answer: Here's the final code:

得到了答案:这是最终的代码:

## CONVERT ALL FILES IN A DIRECTORY

## Load Foreign Library
library(foreign)

## Set working directory in which dtw files can be found)
setwd("~/Desktop")

## Convert all files in wd from DTA to CSV
### Note: alter the write/read functions for different file types.  dta->csv used in this specific example

for (f in Sys.glob('*.dta')) 
  write.csv(read.dta(f), file = gsub('dta$', 'csv', f))

1 个解决方案

#1


1  

If the files are in your current working directory, one way would be to use Sys.glob to get the names, then loop over this vector.

如果文件在您当前的工作目录中,一种方法是使用Sys.glob获取名称,然后循环遍历此向量。

for (f in Sys.glob('*.dta')) 
    write.csv(read.dta(f), file = gsub('dta$', 'csv', f))

#1


1  

If the files are in your current working directory, one way would be to use Sys.glob to get the names, then loop over this vector.

如果文件在您当前的工作目录中,一种方法是使用Sys.glob获取名称,然后循环遍历此向量。

for (f in Sys.glob('*.dta')) 
    write.csv(read.dta(f), file = gsub('dta$', 'csv', f))