Maya
Maya

Reputation: 579

How to replace column values with their label

I imported a .sav file and a simple example of what happened:

library("labelled")
data <- data.frame(x = 1:5, y = c("a", "b", "c", "b", "a"))

  x y
1 1 a
2 2 b
3 3 c
4 4 b
5 5 a

stack(attr(data$y, "labels"))

  values     ind
1      a   hello
2      b     bye
3      c see you
4      b     bye
5      a   hello

Basically I don't want labelled data, however I want the 'ind' as column values so

data
  x       y
1 1   hello
2 2     bye
3 3 see you
4 4     bye
5 5   hello

Upvotes: 0

Views: 147

Answers (1)

Edo
Edo

Reputation: 7858

Your reproducible example doesn't work.

Did you mean to write this?

library("labelled")

data <- data.frame(x = 1:5, y = c("a", "b" ,"c" ,"b" ,"a"))
data$y <- labelled(data$y, c("hello" = "a", "bye" = "b", "see you" = "c"))
stack(attr(data$y, "labels"))
#>   values     ind
#> 1      a   hello
#> 2      b     bye
#> 3      c see you

If so, to get the expected result, you can do this:

data$y <- to_factor(data$y)

data
#>   x       y
#> 1 1   hello
#> 2 2     bye
#> 3 3 see you
#> 4 4     bye
#> 5 5   hello

Upvotes: 1

Related Questions