所以我有一个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))
答案 0 :(得分:1)
如果文件在当前工作目录中,一种方法是使用Sys.glob
获取名称,然后循环遍历此向量。
for (f in Sys.glob('*.dta'))
write.csv(read.dta(f), file = gsub('dta$', 'csv', f))