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

StackOverflow https://stackoverflow.com/questions/15707039

  •  30-03-2022
  •  | 
  •  

Frage

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))
War es hilfreich?

Lösung

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))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top