3

How do I set the value labels for multiple variables in a data frame imported from SPSS via haven. This produces variables of the haven_labelled class. I am trying to set the value labels with the [labelled][1] package .

#Fake data
var1<-labelled(sample(seq(1,4,1)), labels=NULL)
var2<-labelled(sample(seq(1,4,1)), labels=NULL)
var3<-labelled(sample(seq(1,4,1)), labels=NULL)
#Provide one variable to make sure I can use the vars() function so I can select out a subset of variables to mutate
out<-labelled(sample(seq(1,4,1)), labels=NULL)
df<-data.frame(var1, var2, var3, out)
#Check that these are haven_labelled as my data are
str(df)
df %>% 
  mutate_at(vars(starts_with('var')),set_value_labels, 
            "Catholic=1",
            "Protestant=2",
            "None=3", 
            "Other=4") %>% 
val_labels()

In the end, I would like each of these four variables to have have the same value labels. This works, but I am trying to simplify the code.


val_labels(df[,c('var1', 'var2', 'var3')])<-c(Catholic=1, Protestant=2, None=3, Other=4)
df
str(df)
as_factor(df)
3
  • Please specify the packages used
    – akrun
    Feb 13, 2020 at 16:55
  • set_value_labels from which package? I loaded haven, but it is not in that
    – akrun
    Feb 13, 2020 at 16:58
  • set_value_labels probably from the labelled package.
    – bcarothers
    Feb 17, 2020 at 23:00

1 Answer 1

3

Just using haven and not labelled this should work--you were very close but you just needed to past the labels as a named vector:

library(dplyr)
library(haven)
library(purrr)

df %>% 
  mutate_at(vars(starts_with('var')), ~labelled_spss(., labels = c("Catholic"=1, "Protestant"=2, "None"=3, "Other"=4))) %>% 
  map(print_labels)

Labels:
 value      label
     1   Catholic
     2 Protestant
     3       None
     4      Other

Labels:
 value      label
     1   Catholic
     2 Protestant
     3       None
     4      Other

Labels:
 value      label
     1   Catholic
     2 Protestant
     3       None
     4      Other
$var1
<Labelled SPSS double>
[1] 1 3 4 2

Labels:
 value      label
     1   Catholic
     2 Protestant
     3       None
     4      Other

$var2
<Labelled SPSS double>
[1] 4 3 1 2

Labels:
 value      label
     1   Catholic
     2 Protestant
     3       None
     4      Other

$var3
<Labelled SPSS double>
[1] 3 4 2 1

Labels:
 value      label
     1   Catholic
     2 Protestant
     3       None
     4      Other

$out
<Labelled double>
[1] 3 1 4 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.