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.
mtcars %>% select(cyl) %>% .$cyl %>% plyr::mapvalues(c(4,6,8), c('a', 'b', 'c'))%>% as.data.frame()
– Whitnellmtcars %>% mutate(x = mapvalues(cyl, c(4, 6, 8), c("a", "b", "c"))) %>% select(x)
– Perfectly.$cyl
do? – Edbertcyl
as vector. Usually, the syntax in dplyr is to apply the function insidemutate
(as Richard Scriven showed), but I was just imitating your code – Whitnellcyl
to.
So this solution only sort of works. – Edbertmtcars %>% transmute(cyl = factor(cyl, labels = c("a", "b", "c")))
similarly – Lavondamtcars %>% .$cyl %>% plyr::mapvalues(c(4,6,8), c('a', 'b', 'c')) %>% data.frame(cyl=.)
– Whitnell