我想在 df 上 purrr::map 并为每一列生成一个带有分组变量的箱线图。示例尝试:
mtcars |> select(am, gear, carb) |>
map(~ ggplot() +
geom_boxplot(aes(y = .x, fill = factor(mtcars$cyl))) +
labs(title = .y))
结果:
dots_list(..., title = title, subtitle = subtitle, caption = caption, : ... 列表包含少于 2 个元素
期望的结果:
.x
将是来自 df_
,分配分组变量cyl
.y
我如何 purrr::map 覆盖 am、gear 和 carb 的 3 列,为每个列生成一个按 cyl 分组/拆分并使用 hte native pipe 的箱线图?
使用
purrr::map
,它不会定义.y
,但我推断您打算将其作为列名。使用purrr::imap
你的代码工作。
library(dplyr)
library(purrr)
library(ggplot2)
mtcars |> select(am, gear, carb) |>
imap(~ ggplot() +
geom_boxplot(aes(y = .x, fill = factor(mtcars$cyl))) +
labs(title = .y))
可选,我用
patchwork
制作了上面的三重图:
library(patchwork)
map(c("am", "gear", "carb"), ~ mtcars |>
ggplot() +
geom_boxplot(aes(y = .data[[.x]], fill = as.factor(cyl))) +
labs(title = .x)) |>
Reduce(`+`, x = _)
...虽然这也可以通过刻面更容易地完成。
这个有用吗?
library(tidyverse)
map(c("am", "gear", "carb"), ~ mtcars |>
ggplot() +
geom_boxplot(aes(y = .data[[.x]], fill = as.factor(cyl))) +
labs(title = .x))