带有 SPSS 的 R 包 Haven 中的变量标签

Variable labels in the R package Haven with SPSS

我正在尝试使用 haven 包从 SPSS por 文件访问变量标签(这是变量的描述)。我可以用外国包裹做得很好,但我想用避风港。有什么建议吗?

# Using foreign I can get the variable labels
with_foreign <- foreign::read.spss(mydata.por)
attr(with_foreign, "variable.labels")

# With haven I get null
with_haven <- haven::read_spss(mydata.por)
attr(with_haven, "variable.labels")

# Some things I've experimented with
labelled::var_label(with_haven) # NULL
attributes(with_haven) # Not useful
as_factor(with_haven$var1) # Gives me definitions for factor levels (not what I need)

read_spss 中所述,标签存储为每列的属性,而不是 data.frame 的属性。尝试

lapply(with_haven, function(x) attributes(x)$label)

该函数可以解决问题。

sapply(with_haven, attr,"label")