我试图了解如何使用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))
Run Code Online (Sandbox Code Playgroud)
我期待着#2的例子可以工作,但我必须缺少或不理解某些东西.我想要#1没有控制台输出的情节.
cam*_*lle 10
我不确定为什么它plot
在你的第四个例子中诚实地与基础R一起使用.但是ggplot
,您需要明确告诉walk
您要打印它.或者正如评论所示,walk
将返回情节(我在第一次评论时错过了)但不打印它们.所以你可以使用walk
保存图,然后写第二个语句来打印它们.或者在一个walk
电话中完成.
这里有两件事:我在里面使用函数符号walk
,而不是purrr
缩写~
符号,只是为了让它更清楚发生了什么.我也将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)
})
Run Code Online (Sandbox Code Playgroud)
由reprex包(v0.2.0)于2018-05-09创建.