2

所以我有一个 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")

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

## 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]]

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

审查的答案包括:

无需 Stata 软件即可将 Stata .dta 文件转换为 CSV

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

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

谢谢!!

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

1 回答 1

2

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.

for (f in Sys.glob('*.dta')) 
    write.csv(read.dta(f), file = gsub('dta$', 'csv', f))
于 2013-03-29T16:21:11.753 回答