2013-03-29 15 views
1

因此,我有一個dta到csv轉換的單個實例,我需要對目錄中的所有文件重複它。對此有很大的幫助,但我還沒有到達那裏。這裏的單實例正確的措辭爲一個循環將所有.dta文件轉換爲目錄中的.csv

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

回答

1

如果這些文件是在當前工作目錄,一種方法是使用Sys.glob得到的名稱,然後通過這個載體循環。

for (f in Sys.glob('*.dta')) 
    write.csv(read.dta(f), file = gsub('dta$', 'csv', f)) 
+0

這完全是完美的,花了7分鐘的時間回答問題。我應該在一個小時前問過 - – anjarp

相關問題