3

I am getting familiar with recode from dplyr V0.5. Am I missing something? Seems like Recode from car is way more efficent. Unless I am doing something wrong:

This works:

x <- c("a", "b", "c")
y <- dplyr::recode(x, a = 1, b = 2, c= 3)
y

But not when you have a factor:

xf <- factor(c("a", "b", "c"))
yf<- dplyr::recode(xf, a = 1, b = 2, c= 3)
Error: `a` has type 'double' not 'character'

Seems like you have to treat it as character and use recode_factor so that it goes back to factor

Dyf <- dplyr::recode_factor(as.character(xf), a = 1, b = 2, c= 3)
Dyf

That would work but seems pretty verbose??? Recode from car would do it simply with:

Cyf <- Recode(x, " 'a'=1; 'b'= 2; 'c' = 3 ")
Cyf  [1] 1 2 3
Levels: 1 2 3

I am missing something?

THANKS

Bonfil
  • 31
  • 1
  • 4
  • The latest dplyrish tool for factors is "forcats": https://blog.rstudio.org/2016/08/31/forcats-0-1-0/ – Frank Nov 16 '16 at 02:08
  • yeah but I think `forcats` works well with character to character but it doesn't change character to numeric. – Bonfil Nov 16 '16 at 03:21
  • You could put your 1, etc., in quotes in your first `recode` call: `... a = "1", ...` – aosmith Nov 16 '16 at 18:09
  • But that would basically add numbers that are strings, I want to actually turn them into numeric. – Bonfil Nov 18 '16 at 04:24

1 Answers1

0

Looks like dplyr has been enhanced to do what you wanted:

library(dplyr)
#> Warning: package 'dplyr' was built under R version 3.5.3
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
xf <- factor(c("a", "b", "c"))
Eyf<- xf %>% dplyr::recode_factor(a = 1, b = 2, c= 3)
Eyf
#> [1] 1 2 3
#> Levels: 1 2 3
Fyf<- xf %>% dplyr::recode(a = 1, b = 2, c= 3) %>% factor()
Fyf
#> [1] 1 2 3
#> Levels: 1 2 3

Created on 2019-08-28 by the reprex package (v0.3.0)

Arthur Yip
  • 5,810
  • 2
  • 31
  • 50