简体   繁体   中英

How do I use mutate_at with set_value_labels to change the value labels of multiple variables?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM