rhavenlabelled

Turn a Character Vector into Numeric Vector with labels


This seems extremely basic but I cannot find an efficient way to do this:

I have character vector

s<-c("LabelB","LabelX", "LabelE", "LabelE", "LabelX", "LabelD", "LabelB")

What I want is a numeric vector where the numbers can be interpreted ordinally

library(haven)
library(labelled)
labelledS<-c(1,4,3,3,4,2,1)

with labels, i.e. the labels are preserved with

Labels
value    label
1         LabelB
2         LabelD
3         LabelE
4         LabelX

I am open to using other packages besides haven or labelled. As I have many levels and labels, I just want to make sure that this is done without manually recoding the variable.

I tried things like:

MyLevels <- c(1,2,3,4)
names(MyLevels) <- levels(as.factor(s))
labelledS <- labelled(s, as.factor(MyLevels))

However, here the values of the variables remain strings, whereas I want them to be integers.

Thank you very much for your help!


Solution

  • Here is the correct way to do it with haven,

    v1 <- as.integer(factor(s))
    levels = levels(factor_s)
    values = seq_along(levels)
    
    res <- haven::labelled(v1, setNames(object = values, nm = levels))
    
    res
    <labelled<integer>[7]>
    [1] 1 4 3 3 4 2 1
    
    Labels:
     value  label
         1 LabelB
         2 LabelD
         3 LabelE
         4 LabelX