38

かなりの数のパッケージで、関数が呼び出されるコンテキストでは有効ではないシンボル名を渡すことができることに気付きました。これがどのように機能し、自分のコードでどのように使用できるのだろうか?

ggplot2 の例を次に示します。

a <- data.frame(x=1:10,y=1:10)
library(ggplot2)
qplot(data=a,x=x,y=y)

x私の名前空間には存在しyませんが、ggplot はそれらがデータ フレームの一部であることを理解し、それらの評価を有効なコンテキストに延期します。私は同じことをやってみました:

b <- function(data,name) { within(data,print(name)) }
b(a,x)

ただし、これは惨めに失敗します。

Error in print(name) : object 'x' not found

私は何を間違っていますか?これはどのように作動しますか?

:これは、変数名をrの関数に渡すの複製ではありません

4

4 に答える 4

17

match.callたとえば、次を使用してこれを行うことができます。

b <-  function(data,name) {

  ## match.call return a call containing the specified arguments 
  ## and the function name also 
  ## I convert it to a list , from which I remove the first element(-1)
  ## which is the function name

  pars <- as.list(match.call()[-1])
  data[,as.character(pars$name)]

}

 b(mtcars,cyl)
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

説明:

match.call は、指定されたすべての引数が完全な名前で指定されている呼び出しを返します。

したがって、ここでの出力match.callは2つのシンボルです。

b <-  function(data,name) {
  str(as.list(match.call()[-1]))  ## I am using str to get the type and name
}

b(mtcars,cyl)
List of 2
 $ data: symbol mtcars
 $ name: symbol cyl

したがって、最初のシンボル mtcars を使用し、2 番目のシンボルを文字列に変換します。

mtcars[,"cyl"]

または同等:

eval(pars$data)[,as.character(pars$name)]
于 2013-10-02T09:46:52.037 に答える