Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

recode() improvements #2268

Closed
GarciaRios opened this issue Nov 26, 2016 · 2 comments
Closed

recode() improvements #2268

GarciaRios opened this issue Nov 26, 2016 · 2 comments

Comments

@GarciaRios
Copy link

@GarciaRios GarciaRios commented Nov 26, 2016

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)
@hadley
Copy link
Member

@hadley hadley commented Feb 27, 2017

I've fixed the first problem: recode() can now recode factors to any data type.

I have not fixed the second problem, as that code should probably go in haven. In the future, can you please file on issue per issue? It makes life easier for me.

@GarciaRios
Copy link
Author

@GarciaRios GarciaRios commented Feb 27, 2017

Sure, thanks! I will close this issue an post it as a new issue in haven.

@lock lock bot locked as resolved and limited conversation to collaborators Jun 8, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants