2017-10-08 4 views
0

私はプロットを作成し、私が理解していないエラーに遭遇する関数を書こうとしています。ここに簡単な例があります。美的エラーを出さずにNULLをggplotに渡す関数を書く方法

再現例:

library (ggplot2) 
# Sample data 
xdata = 0:20 
ydata = 20:40 
dat <- data.frame(xdata, ydata) 

# This works 
line_p <- ggplot(dat, aes(x = xdata, y = ydata, group = NULL, color = NULL)) + geom_line() 
line_p 

私は、次の動作が、美学のエラーを取得することが期待が、この場合、xとyの変数は同じ長さです。問題は、グループと色のデフォルト値がNULLのようです。私は明示的にNULLをaes_groupとaes_colorと一緒に関数変数として渡そうとしましたが、これもうまくいきませんでした。

# Using a function doesn't work: 

# create function 
line_function <- function(mydata  = dat, 
          xinput  = x, 
          yinput  = y, 
          aes_group = NULL, 
          aes_color = NULL, 
          ...) { 

    lineplot <- ggplot(dat, aes(x = xinput, y = yinput, group = aes_group, color = aes_color)) + geom_line() 
} 


# test the function 
line_test_p <- line_function(
    mydata = dat, 
    xinput = xdata, 
    yinput = ydata 
) 

line_test_p 

明示的な入力

# test the function again with explicit NULL inputs 

line_test2_p <- line_function(
    mydata = dat, 
    xinput = xdata, 
    yinput = ydata, 
    aes_group = NULL, 
    aes_color = NULL 
) 

line_test2_p 

でのテストは、ggplotが機能せずに動作の例のようにNULL値を解釈する汎用的な関数を書くことはできない、または私は何か他のものをしないのです?

ありがとうございます!

答えて

0

つまり、プログラムで美的マッピングを作成するには、aes_stringをチェックする必要があります。変数を格納した文字列の名前を使用して美的マッピングを作成することができます。こうすることで、関数に引数として列名を渡し、対応するプロットを作成するのは簡単です。

あなたの関数の次のバージョンは、私の作品:

# create function 
line_function <- function(mydata  = dat, 
          xinput  = "x", # note the defaults are 
          yinput  = "y", # strings here 
          aes_group = NULL, 
          aes_color = NULL, 
          ...) { 

    ggplot(mydata, # this should be the argument, not the global variable dat 
     # now we create the aes binding with aes_string 
     aes_string(x = xinput, 
        y = yinput, 
        group = aes_group, 
        color = aes_color)) + 
    geom_line() 
} 

そして今、あなたの例を作成するための機能を使用することができます。

# test the function 
line_test_p <- line_function(
    mydata = dat, 
    xinput = "xdata", # note the strings 
    yinput = "ydata" 
) 

# test the function again with explicit NULL inputs 
line_test2_p <- line_function(mydata = dat, 
           xinput = "xdata", # and strings here 
           yinput = "ydata", 
           aes_group = NULL, 
           aes_color = NULL) 

物事はあなたのために動作するはずです。もう一度、documentationをチェックしてください。これにはさまざまな方法があり、目的や好みに応じてさまざまな方法が好きかもしれません。

+0

アンドリュー、ありがとう、ありがとう。ドキュメントを読んだ後、最も単純な変更は、ラインプロットラインを以下のように変更することでした:** lineplot < - ggplot(mydata、aes_(x = xinput、y = yinput、group = aes_group、color = aes_color))+ geom_lineあなたが言及したように関数の変数として** mydata **を使用しているはずです。** dat ** – DaveM

関連する問題