dinsdag 29 november 2016

Execute R code in Stata / Read SPSS data files

On 64-bit Windows OS and on Mac, the -usespss- command does not work. If you want to use SPSS data (or SAS), without quitting Stata, do something like this:

rsource, terminator(END_OF_R) rpath(R_pathname)
library(foreign);
rprecar<-read.spss("precar.sav", convert.f=TRUE);
rprecar
attributes(rprecar);
write.csv(rprecar,"rprecar.csv", na = ".");
q();
END_OF_R

It may be tricky to find your R_pathname. I didn't bother looking up what it is for now - probably the path to the executable (which sucks, because on every computer it will be different). In the example the conversion goes to csv, and there's the missing values ("na") option. The foreign package actually also allows old Stata 9 files, which is just fine and will preserve most labels, variable names, and missing values.

Here's the info for -foreign-:
https://cran.r-project.org/web/packages/foreign/foreign.pdf