D.H*_*ley 5 r ggplot2 dplyr purrr tidyverse
当使用purrr的两个管道和map()函数时,我对数据和变量的传递方式感到困惑.例如,此代码按预期工作:
library(tidyverse)
cars %>%
select_if(is.numeric) %>%
map(~hist(.))
Run Code Online (Sandbox Code Playgroud)
然而,当我尝试使用ggplot类似的东西时,它表现得很奇怪.
cars %>%
select_if(is.numeric) %>%
map(~ggplot(cars, aes(.)) + geom_histogram())
Run Code Online (Sandbox Code Playgroud)
我猜这是因为"." 在这种情况下,将向量传递给aes(),它期望列名.无论哪种方式,我希望我可以使用管道和map()将每个数字列传递给ggplot函数.提前致谢!
您不应该将原始数据传递给美学映射.相反,您应该动态构建data.frame.例如
cars %>%
select_if(is.numeric) %>%
map(~ggplot(data_frame(x=.), aes(x)) + geom_histogram())
Run Code Online (Sandbox Code Playgroud)
cars %>%
select_if(is.numeric) %>%
map2(., names(.),
~{ggplot(data_frame(var = .x), aes(var)) +
geom_histogram() +
labs(x = .y) })
# Alternate version
cars %>%
select_if(is.numeric) %>%
imap(.,
~{ggplot(data_frame(var = .x), aes(var)) +
geom_histogram() +
labs(x = .y) })
Run Code Online (Sandbox Code Playgroud)
还有一些额外的步骤.
map2而不是map.第一个参数是您传递它的数据帧,第二个参数是names该数据帧的矢量,因此它知道要传递什么map.imap(x, ...)它只适用于数据帧和可强制对象.map2(x, names(x), ...)代词来命名图表.| 归档时间: |
|
| 查看次数: |
1432 次 |
| 最近记录: |