文字列(シングルクウォート または ダブルクウォートで囲まれている)で格納されている変数をggplotのaes()内の列名に指定して作図をしたかったときに躓いたのでメモ。
失敗パターン
.r
> target <- "id_col"
> ggplot(tmp, aes_(x = target_col, y = ctr)) + #列名が""に囲われている状態で指定
geom_col() +
facet_wrap(~group_name)
Error in aes_(x = target_col, y = ctr) : object 'ctr' not found
以下で解決
as.name()で囲うと""がなくなる。
※aes_ を使用することと、列名をそのまま指定している列も同様の形式(as.name("列名"))にしておくこと
.r
ggplot(tmp, aes_(x = as.name(target_col), y = as.name("ctr"))) +
geom_col() +
facet_wrap(~group_name)
その他の失敗パターン
・aesではなくaes_を使用する必要がある
.r
> ggplot(tmp, aes(x = as.names(target_col), y = ctr)) +
geom_col() +
facet_wrap(~group_name)
Error in as.names(target_col) : could not find function "as.names"
・print(target_col, quote=F)
でも文字列の横の""は削除できるが、xに"print(target_col, quote=F)"という1列を指定したと認識されてしまう
.r
> ggplot(tmp, aes(x = print(target_col, quote=F), y = ctr)) +
geom_col() +
facet_wrap(~group_name)