rexpss

r expss recoding factor


I'd like to make small recoding on factor variable using examples from: https://cran.r-project.org/web/packages/expss/vignettes/tables-with-labels.html

a<-c(1,2,1,3,5,4,1,3,2,2,1,1)
a<-factor(a,levels = c(1,2,3,4,5), labels = c("aa", "bb", "cc", "dd", "ee" ))

Let's assume I'd like to create new variable b, where "aa", "bb", "cc" would be now "xx", and rest would be copied. It seems I can not refer to numbers in:

b<-expss::recode(a,1:3~99)

As this return nothing. So I tried to refer by label:

b<-expss::recode(a, c("aa", "bb", "cc")~"xx", TRUE~copy, with_labels=FALSE)

But in this case new variable still has old levels stored:

$levels
[1] "aa" "bb" "cc" "dd" "ee" "xx"

$class
[1] "factor"

So what should be the right approach to get new variable only with "xx", "dd", "ee" levels?


Solution

  • We can wrap with droplevels to drop those unused levels

    b <- droplevels(expss::recode(a, c("aa", "bb", "cc")~"xx",
            TRUE~copy, with_labels=FALSE))
    levels(b)
    #[1] "dd" "ee" "xx"