rr-haven

How to write unique variable names with write_sav


I'm trying to write an SPSS file with some haven_labelled variables and factors that are created from that variable. It's just convenient for me and my use case to use nearly identical variable names. I've used all lower case for the haven_labelled variables and title case for the respective factor variable.

When I export the data frame with write_sav, the SPSS records the variable name of the title case factor with var1, rather than the title case, in this case Francophone. Note that when I change the name of the variable significantly, it prints the variable name.

#This makes the data frame of haven labelled variable and a corresponding factor
test<-structure(list(francophone = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), labels = c(Francophone = 1, `Not Francophone` = 0), label = "Dichotomous variable, R is francophone", class = c("haven_labelled", "vctrs_vctr", "double")), Francophone = structure(c(1L, 1L, 1L,1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Not Francophone", "Francophone"), label = "Dichotomous variable, R is francophone", class = "factor")), row.names = c(NA,-10L), class = c("tbl_df", "tbl", "data.frame"))

#Create a second factor variable equivalent to the first factor, but with a different variable name
test$Franco<-test$Francophone
library(tidyverse)
library(haven)
#Write out the file; sorry I do not know how to use tmpfile() in this case. 
test %>% 
  write_sav(., path="~/Desktop/test2.sav")

Image of SPSS File


Solution

  • To close the loop, variable names in SPSS have to be unique: https://www.ibm.com/docs/en/spss-statistics/version-missing?topic=list-variable-names

    This has always been the case (and will probably not change).