【发布时间】:2013-03-20 09:05:07
【问题描述】:
所以我有一个 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]]
但我不确定正确的语法、表达式等。在查看了以下出色的解决方案后,我只是感到困惑(不一定会出错)并准备手动进行 - 优雅方式的快速提示遍历目录中的每个文件并进行转换?
审核的答案包括:
Convert Stata .dta file to CSV without Stata software
applying R script prepared for single file to multiple files in the directory
Reading multiple files from a directory, R
谢谢!!
得到答案:这是最终代码:
## 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))
【问题讨论】: