Tuesday, June 19, 2012

Batch Convert files from SPSS into Stata format

# Batch Convert files from SPSS into Stata format (using R)
# Written by Francis Smart [econometricsbysimulation.com]

# a. First install R (http://www.r-project.org/)

# b. Next install the package  foreign  from the Package Menu by selecting "Install Packages" [Packages>Install Package(s)>Select Closest Mirror>foreign].

# Now the following code should work:

# First load the foreign package
library(foreign)

# Set working directory (directory or super-directory (opposite of sub?) in which sav files can be found)
setwd("c:/*my_directory1*/*my_directory2*/")
# In R you must specify directories with either / or \\
# You must replace *my_directory* with the directory where to look for the sav files.

# Create a list of all of the sav files in the directory
dta_list<-dir(pattern = ".sav$", recursive=T, ignore.case = T)
# The default in this code is to look for files recursively (meaning within sub-directories).
# If you only want to look within the specific directory turn recursive to equal F.

# Loop through each member of the list
for(self in dta_list){

# Display what file will be read
  cat("Reading file ", self, "\n")

# Import the data as a dataframe (a class of objects in R intended for spreadsheet type data)
  data <- as.data.frame(read.spss(self, use.value.labels=TRUE, max.value.labels=Inf, to.data.frame=TRUE))

# Save the file substituting the sav extension for the dta extension
  write.dta(data, sub(".sav",".dta",self))
# dta files will be saved to the same directory as the orignal files
}

# I do not know how to correct the displayed error.  

# If you have any suggestions, please email me.

# Note this loop could easily be modified to accommodate many file formats since the "foreign" package  can handle many different types of file formats.

5 comments:

  1. Another option in Stata is the SSC -usespss-.

    ReplyDelete
  2. Good point. I have that listed under my other post

    http://www.econometricsbysimulation.com/2012/06/3-ways-of-loading-spss-sav-files-into.html

    However, I found that the package does not work with 64 bit system so it is not useful to me.

    ReplyDelete
  3. This was so helpful - thanks so much!!

    ReplyDelete
  4. Thanks a lot, it's really quick and efficace with 64 bit system!

    ReplyDelete