我试图了解如何使用walk
静默(不打印到控制台)返回管道中的ggplot2
图。
library(tidyverse)
# EX1: This works, but prints [[1]], [[2]], ..., [[10]] to the console
10 %>%
rerun(x = rnorm(5), y = rnorm(5)) %>%
map(~ data.frame(.x)) %>%
map(~ ggplot(., aes(x, y)) + geom_point())
# EX2: This does not plot nor print anything to the console
10 %>%
rerun(x = rnorm(5), y = rnorm(5)) %>%
map(~ data.frame(.x)) %>%
walk(~ ggplot(., aes(x, y)) + geom_point())
# EX3: This errors: Error in obj_desc(x) : object 'x' not found
10 %>%
rerun(x = rnorm(5), y = rnorm(5)) %>%
map(~ data.frame(.x)) %>%
pwalk(~ ggplot(.x, aes(.x$x, .x$y)) + geom_point())
# EX4: This works with base plotting
10 %>%
rerun(x = rnorm(5), y = rnorm(5)) %>%
map(~ data.frame(.x)) %>%
walk(~ plot(.x$x, .x$y))
我期待着#2的例子可以工作,但我必须缺少或不理解某些东西。我希望#1中没有控制台输出的情节。
答案 0 :(得分:8)
我不确定为什么它在你的第四个例子中诚实地使用基础R plot
。但是对于ggplot
,您需要明确告诉walk
您希望它打印。或者正如评论所示,walk
将返回情节(我在第一次评论时错过了)但不打印它们。因此,您可以使用walk
来保存图,然后编写第二个语句来打印它们。或者在一次walk
电话中进行。
这里有两件事:我在walk
内使用功能表示法,而不是purrr
的缩写~
表示法,只是为了让它更清楚“#39}继续我也将10改为4,这样我就不会淹没每个人的屏幕上的大量情节。
library(tidyverse)
4 %>%
rerun(x = rnorm(5), y = rnorm(5)) %>%
map(~ data.frame(.x)) %>%
walk(function(df) {
p <- ggplot(df, aes(x = x, y = y)) + geom_point()
print(p)
})
由reprex package(v0.2.0)创建于2018-05-09。