【发布时间】:2020-02-06 04:37:34
【问题描述】:
我创建了一个自定义函数,可以使用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 月 8 日创建
【问题讨论】: