【问题标题】:How to control the row/column-wise printing of plots when using apply functions使用应用函数时如何控制绘图的行/列打印
【发布时间】:2021-05-05 00:23:45
【问题描述】:

考虑以下数据框:

dat <- data.frame(
  ID = c(1:200),
  var1 = rnorm(200),
  var2 = rnorm(200),
  var3 = rnorm(200),
  var4 = rnorm(200)
)

我们想使用lapply() 函数将ggpubr 包中的ggqqplot 函数应用于dat 的第2:4 列:

library(tidyverse)
library(ggpubr)
vars <- paste0(names(dat[,2:5]))
lapply(vars, FUN=ggqqplot, data=dat)

这很好用,但我们想并排打印数字(例如,2 行 2 列)。我们如何使用 apply 框架来做到这一点?

【问题讨论】:

    标签: r iteration apply lapply


    【解决方案1】:

    ggqqplot 允许使用参数facet_by 的构面(检查?ggqqplot),因此您所要做的就是将您的数据转换为构面友好的长格式数据。见下文

    dat_melt <- reshape2::melt(dat, measure.vars = vars) # converts data into long-form
    ggqqplot(dat_melt, x="value", facet.by = "variable")
    

    编辑:

    如果你还想使用apply函数,下面是我能想到的最简单的解决方案

    plist <- lapply(vars, FUN = function (x) ggqqplot(dat,x = x))
    cowplot::plot_grid(plotlist = plist, ncol = 2)
    

    或管道友好的等价物

    lapply(vars, FUN = function (x) ggqqplot(dat,x = x)) %>%
      {cowplot::plot_grid(plotlist=.,ncol = 2)}
    

    【讨论】:

    • 这解决了问题,要在tidyverse 框架中添加类似的解决方案,我会添加dat%&gt;%pivot_longer(-c(1), names_to='var', values_to='val')%&gt;%ggqqplot(., x='val', facet.by='var')。不过,这个问题是为了与apply 系列函数有关,所以我会看看是否有人在该框架中提供了解决方案
    猜你喜欢
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多