使用`map`系列使用自定义绘图功能进行迭代

时间:2019-10-08 21:00:13

标签: r ggplot2 dplyr purrr

我创建了一个自定义函数,可以使用ggplot2包来绘制直方图。我想遍历数据框的每一列以为每一列生成直方图。

library(tidyverse)

#Making function to facilitate variable iteration. Supply data frame and single variable name
histogram_fun = function(df = model_data, x = "variable_name") {
     ggplot(df, aes(x = .data[[x]] )) +
         geom_histogram() + 
         labs(x = x)
}

当我尝试histogram_fun(gss_cat, "age")时,我得到了预期的直方图。但是,如果我想遍历变量yearagetvhours,我会尝试类似的尝试,但无济于事:

gss_numeric <- gss_cat %>% select_if(is.numeric) %>% names
gss_numeric
#> [1] "year"    "age"     "tvhours"

gss_cat %>% select(gss_numeric) %>% map(histogram_fun(df = ., x = gss_numeric))
#> Can't convert a `gg/ggplot` object to function

如何使用mapwalk函数正确地迭代选择?

reprex package(v0.3.0)于2019-10-08创建

1 个答案:

答案 0 :(得分:1)

这里是将字符串转换为sym bol并求值(!!

的一种选择。
library(dplyr)
library(purrr)
library(ggplot2)
histogram_fun <- function(data, x ) {
  ggplot(data, aes(!! rlang::sym(x) )) +
     geom_histogram() + 
     labs(x = x)
}

gss_numeric <- c("mpg", "disp")
p1 <- map(gss_numeric, ~ histogram_fun(mtcars, .x))
library(ggpubr)
p1 <- map(gss_numeric, ~ histogram_fun(mtcars, .x))
ggarrange(p1[[1]], p1[[2]], ncol = 2)