Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using plyr::mapvalues with dplyr

plyr::mapvalues can be used like this:

mapvalues(mtcars$cyl, c(4, 6, 8), c("a", "b", "c"))

But this doesn't work:

mtcars %>%
dplyr::select(cyl) %>%
mapvalues(c(4, 6, 8), c("a", "b", "c")) %>%
as.data.frame()

How can I use plyr::mapvalues with dplyr? Or even better, what the dplyr equivalent?

like image 761
luciano Avatar asked Jan 18 '15 19:01

luciano


2 Answers

2020 Update: plyr is now a "retired" package and its official guidance suggests using the actively-improved and maintained dplyr package instead. So it's preferable to use only dplyr, in this case dplyr::recode() as in the other answer, and avoid plyr entirely.

To use plyr::mapvalues() with dplyr:

To use it and return a one-column data.frame:

mtcars %>%
  transmute(cyl = plyr::mapvalues(cyl, c(4, 6, 8), c("a", "b", "c")))

Or if you want a single vector output, like in your working example, use pull:

mtcars %>%
  pull(cyl) %>%
  plyr::mapvalues(., c(4, 6, 8), c("a", "b", "c"))

If you are using both dplyr and plyr simultaneously, see this note from the dplyr readme:

You'll need to be a little careful if you load both plyr and dplyr at the same time. I'd recommend loading plyr first, then dplyr, so that the faster dplyr functions come first in the search path. By and large, any function provided by both dplyr and plyr works in a similar way, although dplyr functions tend to be faster and more general.

Though note that you can call mapvalues using plyr::mapvalues if dplyr is loaded without needing to load plyr.

like image 152
Sam Firke Avatar answered Oct 03 '22 09:10

Sam Firke


As the questions also mentions

Or even better, what the dplyr equivalent?

The equivalent is recode.

http://www.cookbook-r.com/Manipulating_data/Renaming_levels_of_a_factor/

name <- c("John", "Clara", "Smith")
sex <- c(1,2,1)
age <- c(30,32,54)
df <- data.frame(name,sex,age)
df %>% mutate(sex=recode(sex,
`1`="Male",
`2`="Female"))

This will "mapvalues" 1 to Male and 2 to Female.

like image 41
Yash Avatar answered Oct 03 '22 09:10

Yash