2

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))
Community
  • 1
  • 1
anjarp
  • 67
  • 1
  • 6

1 Answers1

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))
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113
  • This is exactly perfect and took 7 minutes from question to answer. I should've asked SO an hour ago -- – anjarp Mar 29 '13 at 16:37