使用plyr :: mapvalues与dplyr [英] Using plyr::mapvalues with dplyr
问题描述
plyr :: mapvalues
可以这样使用:
mapvalues(mtcars$cyl, c(4, 6, 8), c("a", "b", "c"))
但这不行:
mtcars %>%
dplyr::select(cyl) %>%
mapvalues(c(4, 6, 8), c("a", "b", "c")) %>%
as.data.frame()
如何使用 plyr :: mapvalues
与
dplyr
?或者更好的是,什么 dplyr
等价?
How can I use plyr::mapvalues
with dplyr
? Or even better, what the dplyr
equivalent?
推荐答案
使用它并返回一列data.frame:
To use it and return a one-column data.frame:
mtcars %>%
transmute(cyl = plyr::mapvalues(cyl, c(4, 6, 8), c("a", "b", "c")))
或者如果您想要一个矢量输出,就像您的工作示例中一样,从magrittr软件包尝试 use_series
:
Or if you want a single vector output, like in your working example, try use_series
from the magrittr package:
library(magrittr)
mtcars %>%
use_series(cyl) %>%
plyr::mapvalues(., c(4, 6, 8), c("a", "b", "c"))
如果您同时使用dplyr和plyr,请参阅 dplyr自述文件中的本说明:
If you are using both dplyr and plyr simultaneously, see this note from the dplyr readme:
如果您同时在
上加载plyr和dplyr,那么您需要小心谨慎。我建议先加载plyr然后dplyr,以便
更快的dplyr函数在搜索路径中首先出现。通过和
大,由dplyr和plyr提供的任何函数都以类似的
方式工作,尽管dplyr函数往往更快更通用。
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.
虽然注意,如果dplyr,您可以使用 plyr :: mapvalues
调用 mapvalues
被加载而不需要加载plyr。
Though note that you can call mapvalues
using plyr::mapvalues
if dplyr is loaded without needing to load plyr.
这篇关于使用plyr :: mapvalues与dplyr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!