Using plyr::mapvalues with dplyr

人盡茶涼 提交于 2019-11-30 16:43:20

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28013652/using-plyrmapvalues-with-dplyr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!