glue::glue()による動的なファイル名/クエリの生成
Rのglue::glue()を使うと、{}
で囲った変数名に応じた変数で補完した文字列が生成される。
library(glue) for (i in 1:3){ print(glue('hoge{i}')) } # => # hoge1 # hoge2 # hoge3
glueを利用して、動的にファイルを作成する。以下では、irisをspecies毎に分けたggplotの結果を、speciesに応じたファイル名にして保存している。
library(tidyverse) library(glue) df = iris %>% as_tibble() plot_wrapper = function(df, species) { g = df %>% filter(Species == species) %>% ggplot(aes(x=Sepal.Length, y=Sepal.Width, color = Species)) + geom_point() + theme(panel.grid.major.x = element_blank()) ggsave(glue("figure/plot_{species}.png"), plot = g, width = 14, height = 6) } for (i in c('setosa','versicolor','virginica')){ plot_wrapper(df, i) }
他にも、detaframeから直接読み取った値を変数のようにして作成したり、query作成特化の関数もあるそうな。