LoginSignup
22
19

More than 5 years have passed since last update.

可変長引数が最初にある関数に対する do.call() のやりかた

Posted at

ggplot2 でちょっとはまったのでメモ。
複数のグラフを一枚のプロットに埋め込むには gridExtra パッケージの grid.arrange() を使えばいいらしい。
参照:異なる複数のグラフを一つの図に描画 - Triad sou.

library("ggplot2")
library("gridExtra")

data(iris)

graph.list <- lapply(1:4, function(i) {
  name <- colnames(iris)[i]
  d <- data.frame(Species=iris[,5], y=iris[,i])
  ggplot(d, aes(x=Species, y=y, fill=Species)) + geom_boxplot() + 
    xlab(NULL) + ylab(NULL) + ggtitle(name)
})

grid.arrange(graph.list[[1]], graph.list[[2]], graph.list[[3]], 
             graph.list[[4]], ncol=2, nrow=2)

複数のグラフを一枚のプロットに埋め込む

でもさ、最後の行、graph.list[[1]], ..., graph.list[[4]] っていちいち書くのめんどくさいよね。
この graph.list をそのまま grid.arrange() に渡したい。
フツ―に下記のように書くと、エラーになる。

grid.arrange(graph.list, ncol=2, nrow=2)
 以下にエラー arrangeGrob(..., as.table = as.table, clip = clip, main = main,  : 
  input must be grobs!

こういうときは、do.call() を使う。
do.call() はリストを list[[1]], ..., list[[n]] みたいに展開して関数に渡してくれるナイスなやつです。
使い方は do.call(関数名, 引数リスト)

args <- list(graph.list, ncol=2, nrow=2)
do.call(grid.arrange, args)
 以下にエラー arrangeGrob(..., as.table = as.table, clip = clip, main = main,  : 
  input must be grobs!

しかし、これもうまくいかなかった。
なぜ?
原因は grid.arrange() は可変長引数を最初に持つからっぽい。
こういうときは、次のように書けばいいみたい。

args <- c(graph.list, list(ncol=2, nrow=2))
do.call(grid.arrange, args)

プロット成功!

おー、でけた!

以上です。

22
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
19