2

I imported a sav file with a lot of columns that are labelled. Instead of labelled data, I would like to get the labels as values.

library(tidyverse)
df <- structure(list(color = structure(c(1, 1, 1, 1, 2, 3, 2, 1, 1, 1), 
 label = "color", 
 format.spss = "F1.0", 
 labels = c(`blue` = 1, `yellow` = 2, `pink` = 3), 
 class = c("haven_labelled", "vctrs_vctr", "double"))), 
 row.names = c(NA,-10L), 
 class = c("tbl_df", "tbl", "data.frame"))
# color
# 1 1
# 2 1
# 3 1
# 4 1
# 5 2
# 6 3
# 7 2
# 8 1
# 9 1
# 10 1

What I would like to get

# color
# 1 blue
# 2 blue
# 3 blue
# 4 blue
# 5 yellow

I've been looking for hours, but only find ways to remove the labels which results in a df with the numeric values and the labels completely gone (basically the first df in this post, without label information). Any suggestions?

asked May 4, 2021 at 15:26

1 Answer 1

2

Perhaps haven::as_factor is what you need?

It also works with the core tidyverse packages loaded i.e. library(tidyverse) and using the as_factor function. I suspect loading the tidyverse installs functions from haven, including the as_factor function.


haven::as_factor(df)
#> # A tibble: 10 x 1
#> color 
#> <fct> 
#> 1 blue 
#> 2 blue 
#> 3 blue 
#> 4 blue 
#> 5 yellow
#> 6 pink 
#> 7 yellow
#> 8 blue 
#> 9 blue 
#> 10 blue

Created on 2021年05月04日 by the reprex package (v2.0.0)

answered May 4, 2021 at 15:57
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.