7

I want to extract the $label attribute from a haven labelled data set and it always failed when using the column index and not the column name.

What I did:

library(haven)
df <- read_sav(mydata.sav)

attributes(df$gender) 
#$`label`
#[1] "Are you ...?"
#
#$format.spss
#[1] "F1.0"
#
#$display_width
#[1] 0
#
#$class
#[1] "haven_labelled"
#
#$labels
#
#female male
# 
#     1        2 

but using:

attributes(df[,2])
#  $`names`
#[1] "gender"
#
#$row.names
#....
#
#$class
#
#[1] "tbl_df"     "tbl"        "data.frame"

because there are a lot variables in the dataset and I don't use SPSS it would be very helpful if anyone do have an idea how to solve that issue by using the column index instead of the variable name

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
roland
  • 71
  • 3

1 Answers1

7

This can be done using the [[ extractor, see the famous question on the Difference between [ and [[.
Tested with the example in help('read_spss').

library(haven)

path <- system.file("examples", "iris.sav", package = "haven")
df1 <- read_sav(path)
attributes(df1[[5]])$labels
#    setosa versicolor  virginica 
#         1          2          3 
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66