我如何使用原生管道和占位符内的ggploy geom?
当传递一个data.Frame来进行ggmap时,本机管道工作得很好,但是在geom中,当我想要过滤原始的data.Frame时,我需要使用‘magrittr’管道.
因此,这项功能运行良好:
mtcars |>
ggplot() +
geom_col(data = . %>% filter(cyl == 4),
aes(x = gear, y = mpg),
fill = "grey80") +
geom_text(data = . %>% filter(cyl == 4 & gear == 3),
aes(x = gear,
y = mpg,
label = "ooo"), color = "tomato3") +
theme_minimal()
使用匿名函数,我可以完全切换到本地管道:
mtcars |>
ggplot() +
geom_col(data = (\(x) filter(x, cyl == 4)),
aes(x = gear, y = mpg),
fill = "grey80") +
geom_text(data = (\(x) filter(x, cyl == 4 & gear == 3)),
aes(x = gear,
y = mpg,
label = "ooo"), color = "tomato3") +
theme_minimal()
但是,有没有一种很好的方法来使用R的本地管道操作符和占位符来执行相同的操作呢?
这将引发错误"Invalid Use of PIPE PLACEHOLDER":
mtcars |>
ggplot() +
geom_col(data = _ |> filter(cyl == 4),
aes(x = gear, y = mpg),
fill = "grey80") +
geom_text(data = _ |> filter(cyl == 4 & gear == 3),
aes(x = gear,
y = mpg,
label = "ooo"), color = "tomato3") +
theme_minimal()