【问题标题】:Using purrr::walk() and ifelse to produce ggplots使用 purrr::walk() 和 ifelse 生成 ggplots
【发布时间】:2019-05-27 14:18:49
【问题描述】:

我有一个数据框,每个人一行。这些列是一个结果变量,然后是该结果的一堆潜在预测变量。作为我的数据分析的初步步骤,我想使用 ggplot 可视化每个预测变量及其与结果的关联。我想要连续变量的直方图和分类的条形图。

我的尝试是

numeric <- c(0,1.1,2.4,3.1,4.0,5.9,4.2,3.3,2.2,1.1)
categorical <- as.factor(c("yes","no","no","yes","yes","no","no","yes","no","no"))
outcome <- as.factor(c("alive","dead","alive","dead","alive","dead","alive","dead","alive","dead"))
df <- data.frame(num = numeric, cat = categorical, outcome = outcome)
predictors <- c("num", "cat")
predictors %>%
    walk(print(ggplot(df, aes(x=., fill=outcome)) +
    {ifelse(class(.) == "factor", geom_bar(position="fill"), geom_histogram(position="fill", bins=10))}))

但我得到了错误

Error in rep(no, length.out = length(ans)): attempt to replicate an object of type 'environment'
Traceback:

1. predictors %>% walk(print(ggplot(df, aes(x = ., fill = outcome)) + 
 .     {
 .         ifelse(class(.) == "factor", geom_bar(position = "fill"), 
 .             geom_histogram(position = "fill", bins = 10))
 .     }))
2. withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
3. eval(quote(`_fseq`(`_lhs`)), env, env)
4. eval(quote(`_fseq`(`_lhs`)), env, env)
5. `_fseq`(`_lhs`)
6. freduce(value, `_function_list`)
7. withVisible(function_list[[k]](value))
8. function_list[[k]](value)
9. walk(., print(ggplot(df, aes(x = ., fill = outcome)) + {
 .     ifelse(class(.) == "factor", geom_bar(position = "fill"), 
 .         geom_histogram(position = "fill", bins = 10))
 . }))
10. map(.x, .f, ...)
11. as_mapper(.f, ...)
12. print(ggplot(df, aes(x = ., fill = outcome)) + {
  .     ifelse(class(.) == "factor", geom_bar(position = "fill"), 
  .         geom_histogram(position = "fill", bins = 10))
  . })
13. ifelse(class(.) == "factor", geom_bar(position = "fill"), geom_histogram(position = "fill", 
  .     bins = 10))   # at line 9 of file <text>

我希望这段代码产生两个图

我的实际数据集有超过 20 个预测变量,所以我想要一种生成 20 多个 ggplots 的好方法,并且理想情况下将其保持在这样的管道格式中,这样我可以在绘图工作后添加额外的步骤。

【问题讨论】:

  • 当遍历您的预测向量时,class(.) 将始终是字符。你的意思是指你的df的那一列吗?即class(df[[.]])。其次,ifelse不能用于返回这种类型的对象afaik,最好使用标准if

标签: r ggplot2 purrr


【解决方案1】:

这是将predictors 列传递给map 并根据列的class 创建绘图列表的一种方法。

library(tidyverse)
library(rlang)

p1 <- map(predictors, function(p) if (class(df[[p]]) == "factor") 
      ggplot(df, aes(x = !!sym(p), fill=outcome)) + geom_bar(position="fill")
      else
      ggplot(df, aes(x = !!sym(p), fill=outcome)) + 
                 geom_histogram(position="fill", bins=10))

p1[[1]]

p1[[2]]

【讨论】:

  • @pgcudahy 而不是!!sym(p),如果我们只使用p 因为predictors 是字符,这意味着为num 列运行ggplot(df, aes(x="num", fill=outcome)) + geom_histogram(position="fill", bins=10)。其中aes 中的x 被评估为字符串“num”,而不是我们希望它是列numsym 将字符转换为符号,!!(读作 bang bang)将其评估为数据框中的当前上下文,使其按预期工作。
猜你喜欢
  • 2017-07-15
  • 2017-03-05
  • 2020-08-24
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多