recode is great! Here are some suggestions:
Character to numeric in factors
recode nicely recodes from character to numeric...So this works:
x <- c("a", "b", "c")
y <- recode(x, a = 1, b = 2, c= 3)
y
But it won't work with factors even using recode_factor
xf <- factor(c("a", "b", "c"))
yf <- recode(xf, a = 1, b = 2, c= 3)
Error: `a` has type 'double' not 'character'
yf <- recode_factor(xf, a = 1, b = 2, c= 3)
Error: `a` has type 'double' not 'character'
You have to treat it as character and use recode_factor so that it goes back to factor. Seems pretty verbose
recode_factor(as.character(xf), a = 1, b = 2, c= 3)
[1] 1 2 3
Levels: 1 2 3
compatibility with labelled class
df <- data_frame(s1 = c("M", "M", "F"), s2 = c(1, 1, 2)) %>%
set_value_labels(s1 = c(Male = "M", Female = "F"), s2 = c(Yes = 1, No = 2))
dplyr::recode(df$s2, `1`=100,`2`=200)
Error in UseMethod("recode") :
no applicable method for 'recode' applied to an object of class "labelled"
It would also be great if add_value_labels and remove_value_labels could be incorporated to deal with the unnecessary and new values.
Using car::recode would get us something like this.
library(labelled)
library(car)
df <- data_frame(s1 = c("M", "M", "F"), s2 = c(1, 1, 2)) %>%
set_value_labels(s1 = c(Male = "M", Female = "F"), s2 = c(Yes = 1, No = 2))
df$s2 <- car::recode(df$s2, "1=100;2=200")
df <- df %>% add_value_labels(s2 = c(Yes = 100, No = 200)) %>%
remove_value_labels(s2 = c(1,2))
val_labels(df)