'Recoding numeric variables classified as vectors

I am having trouble recoding a four point variable that I want to use for an index. When I try using the recode command I get the error message that the command cannot be applied to the class the variable cases belong to. Is there a package to get around this or a way to change the column's class?

df$v1 <- recode(df$v1, '1'=4, '2'=3, '3'=2, '4'=1)

df <- mutate(df, v1_recode = recode(v1, "1" = 4, "2" = 3, "3" = 2, "4"=1))

Error in UseMethod("recode") : no applicable method for 'recode' applied to an object of class "c('haven_labelled', 'vctrs_vctr', 'double')"

r


Solution 1:[1]

An alternative way to achieve that would be this:

df <- mutate(df, 
         v1_recode =case_when(v1 == "1" ~ 4, 
                              v1 == "2" ~ 3, 
                              v1 == "3" ~ 2, 
                              v1 == "4" ~ 1,
                              TRUE ~ v1))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lucca Nielsen