将 R 值标签导出到 SPSS 文件

Exporting R value labels to SPSS file

我正在与一些只使用 SPSS 的人合作一个项目,尽管我使用 R。我正在尝试在 R 中创建一个数据框,其中包含要导出到 SPSS 的因子变量的变量标签和值标签。但是,一旦我在 SPSS 中打开文件,我得到的是变量名而不是值名。

有人知道如何实现吗?

这是我到目前为止所尝试过的。 mtcars 示例。

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")

更新

我可以使用包 haven 将值标签导出到 SPSS 中,但是变量不能是因子或字符,否则函数将不起作用。这是一个问题,因为这些变量是因素。它们应该是 R 中的因素和 SPSS 中的标称值。

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

好的,这是我找到的解决方案。它适用于 R 和 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")

为此,我使用了 sjPlot 包系列,尤其是 sjlabelled。这与避风港的标签版本略有不同,但对于具有标签属性的 R 数据集也有 write_spss。

小插图 https://strengejacke.github.io/sjlabelled/articles/intro_sjlabelled.html 有很多关于导入和使用带标签的 SPSS 数据的内容,但是 write_spss 文档很简洁,但对我使用 SPSS 的同事有用。