Export R data.frame to SPSS

BurninLeo picture BurninLeo · Oct 13, 2016 · Viewed 14.2k times · Source

There is a package foreign with a function write.foreign() that can write a SPS and CSV file. The SPS file than can read the CSV fiel into SPSS including labels. Fine so far, but there are some issues with that function:

  1. Newer SPSS versions may show an error that you have too few format definitions in DATA LIST
  2. If there are "labels" for numeric variables stored via attr(), these are lost.
  3. Even if the SPSS vesion supports strings up to 32767, the function write.foreign() stops if there are more than 255 in any variable.
  4. Theres a star (*) if any character variables are used, but newer SPSS versions cannot handle that.
  5. The CSV file is comma-separated and does (can) not use quotes, therefore no commas are allowed in strings (character)
  6. Non-ASCII caracters (e.g. umlauts) will crash the import
  7. Should you have a character that contains any NA value, you'll see...

... an error message like this:

Error in if (any(lengths > 255L)) stop("Cannot handle character variables longer than 255") : 
    missing value where TRUE/FALSE needed

I spent a lot of time with that and then found a good posting (http://r.789695.n4.nabble.com/SPSS-export-in-R-package-foreign-td921491.html) to start on and make it better. Here's my result, I'd like to share with you.

Answer

Sam Firke picture Sam Firke · Oct 18, 2016

To export an R data.frame to SPSS, use write_sav from the haven package:

library(haven)
write_sav(mtcars, "mtcars.sav")