14

I'm trying to access the variable labels (this is the description of the variable) from an SPSS por file with the haven package. I can do it just fine with the foreign package but I'd like to use haven. Any suggestions?

# 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)
ZRoss
  • 1,437
  • 1
  • 15
  • 32

2 Answers2

12

As stated in read_spss labels are stored as attributes of each column rather than attributes of the data.frame. Try

lapply(with_haven, function(x) attributes(x)$label)
Ista
  • 10,139
  • 2
  • 37
  • 38
  • 1
    Thanks for the response, what this gives are the labels associated with each variable's factor level. What I want are the variable labels themselves. As an example, you might have a variable `var1` that has levels 0 and 1 that match with "Voted for Obama" or "Voted for Trump". These are the levels that your code will reveal. But `var1` may also have a full definition like "Who did you vote for in 2016" -- and it's this that "variable.labels" extracts using foreign. What I'm looking for are the variable definitions which, in foreign, are called "variable labels". – ZRoss Feb 16 '18 at 15:12
  • Turns out haven 1.1.0 (which is what I was using) didn't give the right variable definitions but 1.1.1 does indeed your code works (and so does `labelled::var_label(with_haven)' from the code in my question). Thanks for your help! – ZRoss Feb 16 '18 at 16:29
  • 1
    Glad you got it figured out. In `haven` variable labels are in the `label` attribute and value labels are in the `labels` attribute. – Ista Feb 16 '18 at 18:06
2

The function does the trick.

sapply(with_haven, attr,"label")

milan
  • 4,782
  • 2
  • 21
  • 39