Proper phrasing for a loop to convert all .dta files to .csv in a directory

非 Y 不嫁゛ 提交于 2021-01-28 18:44:17

问题


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

#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

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

Reading multiple files from a directory, 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:


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


来源:https://stackoverflow.com/questions/15707039/proper-phrasing-for-a-loop-to-convert-all-dta-files-to-csv-in-a-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!