Search code examples
rspss

R: Export data frame to SPSS


I have a data frame which I created by importing a .dat Stata file in this manner:

data = read.dta("TEAdataSTATA2.dta")

I then write data to a text file:

write.table(b , "mydata.txt" , sep="\t")

I then use the text file I created to create an SPSS file in this manner:

write.foreign(b , "mydata.txt" , "DerLeew.sps" , package="SPSS")

However, I get an error:

Error in writeForeignSPSS(df = list(studyid = c("P0008", "P0018", "P0031",  : 
  I cannot abbreviate the variable names to eight or fewer letters

Could someone point out the problem?


Solution

  • SPSS used to only support variable names with 8 or less characters. It looks like the code is writing for this older version of SPSS. It attempts to abbreviate the variables to be shorter, but it fails in your case.

    Part of the code:

     if (is.null(varnames)) {
         varnames <- abbreviate(names(df), 8)
         if (any(sapply(varnames, nchar) > 8))
             stop("I cannot abbreviate the variable names to eight or fewer letters")
         if (any(varnames != names(df)))
             warning("some variable names were abbreviated")
     }
    

    You may need to rename the variables to be shorter before calling this function, or try to find an implementation that can write the newer formats of SPSS.