我创建了一个自定义函数,可以使用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")
时,我得到了预期的直方图。但是,如果我想遍历变量year
,age
和tvhours
,我会尝试类似的尝试,但无济于事:
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
如何使用map
或walk
函数正确地迭代选择?
由reprex package(v0.3.0)于2019-10-08创建
答案 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)