LoginSignup
5
4

More than 5 years have passed since last update.

aesの中でローカル変数を使いたい

Last updated at Posted at 2015-08-16

Q.

aesの中でローカル変数を使おうと以下のコードを試しました。

NG_example.R
library(ggplot2)

xy <- data.frame(x=1:10,y=1:10)

plotfunc <- function(Data, YMul=2){
  ggplot(Data, aes(x=x, y=y*YMul)) + geom_line()
}

plotfunc(xy)

でも以下のエラーが出てうまくいかないです。
以下にエラー eval(expr, envir, enclos) : オブジェクト 'YMul' がありません
どうしたらいいでしょうか?

A.

以下のように、environmentの引数を指定するとうまくいきます。これでローカルの環境で実行できるようになります。

OK_example.R
library(ggplot2)

xy <- data.frame(x=1:10, y=1:10)

plotfunc <- function(Data, YMul=2){
  ggplot(Data, aes(x=x, y=y*YMul), environment=environment()) + geom_line()
}

plotfunc(xy)

参考資料

この記事はStackOverFlowの以下の質問の日本語訳です(一部省略および改変)。
http://stackoverflow.com/questions/10659133/local-variables-within-aes

5
4
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
5
4