psoares
psoares

Reputation: 4883

Exporting R value labels to SPSS file

I'm collaborating on a project with some people who only use SPSS although I use R. I'm trying to create a dataframe in R with variable labels and value labels for factor variables to export to SPSS. However, once I open the file in SPSS, I get the variable names but not the value names.

Does anyone has any idea how to achieve this?

Here what I've tried so far. mtcars example.

mtcars = modify(mtcars,{
    var_lab(mpg) = "Miles/(US) gallon"
    var_lab(cyl) = "Number of cylinders"
    var_lab(disp) = "Displacement (cu.in.)"
    var_lab(hp) = "Gross horsepower"
    var_lab(drat) = "Rear axle ratio"
    var_lab(wt) = "Weight (lb/1000)"
    var_lab(qsec) = "1/4 mile time"
    var_lab(vs) = "V/S"
    var_lab(am) = "Transmission (0 = automatic, 1 = manual)"
    val_lab(am) = c(automatic = 0, manual=1)
    var_lab(gear) = "Number of forward gears"
    var_lab(carb) = "Number of carburetors"
})

spss_data <- haven::write_sav(mtcars, "test_mtcars.sav")

UPDATE

I'm able to export value labels into SPSS using the package haven, however the variable cannot be factor or character otherwise the function doesn't work. This is a problem since these variables are factor. They should be factor in R and nominal in SPSS.

mtcars$am <- labelled(mtcars$am, c(automatic = 0, manual = 1), label = "Transmission")

Upvotes: 3

Views: 1597

Answers (2)

paulb20
paulb20

Reputation: 301

For this, I use the sjPlot family of packages, particularly sjlabelled. This has a marginally different version of labelling from haven, but also write_spss for R datasets that have label attributes.

The vignette https://strengejacke.github.io/sjlabelled/articles/intro_sjlabelled.html has a lot about importing and using the labelled SPSS data, but the write_spss documentation is terse, but works for my SPSS-using colleagues.

Upvotes: 1

psoares
psoares

Reputation: 4883

Okay, here's the solution I've found. It works in R and in SPSS.

# Convert variables to factor using the lfactor package 
library(lfactors)
mtcars$vs <- lfactor(mtcars$vs, levels = c(0,1), labels = c("first", "second"))
mtcars$am <- lfactor(mtcars$am, levels = c(0,1), labels = c("automatic", "manual"))

library(haven)
library(expss)
mtcars = modify(mtcars,{
    var_lab(mpg) = "Miles/(US) gallon"
    var_lab(cyl) = "Number of cylinders"
    var_lab(disp) = "Displacement (cu.in.)"
    var_lab(hp) = "Gross horsepower"
    var_lab(drat) = "Rear axle ratio"
    var_lab(wt) = "Weight (lb/1000)"
    var_lab(qsec) = "1/4 mile time"
    var_lab(vs) = "V/S"
    var_lab(am) = "Transmission (0 = automatic, 1 = manual)"
    var_lab(gear) = "Number of forward gears"
    var_lab(carb) = "Number of carburetors"
})

spss_data <- haven::write_sav(mtcars, "test_mtcars.sav")

Upvotes: 2

Related Questions