The problem is fairly simple - if I take a df and perform a few filtering steps on it, I'd like to be able to pipe the output of those into a ggplot function and use the unique value of a particular column as the title. Works with the magrittr pipe and curly braces:
starwars %>%
filter(hair_color == "blond") %>%
{
ggplot(data = ., aes(x = height, y = mass, col = birth_year)) +
geom_point() +
labs(title = unique(.$species))
}
Doesn't work with the base pipe equivalent:
starwars |>
filter(hair_color == "blond") |>
{
ggplot(data = _, aes(x = height, y = mass, col = birth_year)) +
geom_point() +
labs(title = unique(.$species))
}
Error in { :
function '{' not supported in RHS call of a pipe (<input>:3:7)
Other than assigning the df before calling ggplot, are there any other options?
1) Wrap the input in a list having component name . and pass that to with
.
library(dplyr)
library(ggplot2)
starwars |>
filter(hair_color == "blond") |>
list(. = _) |>
with(ggplot(., aes(x = height, y = mass, col = birth_year)) +
geom_point() +
labs(title = unique(.$species))
)
2) Another possibility is to use group_modify
:
starwars |>
filter(hair_color == "blond") |>
group_modify(~ ggplot(., aes(x = height, y = mass, col = birth_year)) +
geom_point() +
labs(title = unique(.$species))
)