2

ユーザーが提供する数学関数(x ^ 2など)を使用してさまざまなことを実行する関数を作成したいと思います。たとえば、次のようになります。

#-----------------nonworking code---------------------
foo <- function(FUN, var){
      math_fun <- function(x){
           FUN
      }
   curve(math_fun, -5, 5)     #plot the mathematical function
   y = math_func(var)         #compute the function based on a user provided x value.
   points(x=var, y=y)         #plot the value from the last step.
}

#A user can use the function defined above in a way as shown below:
Function <- x^2 + x
foo(FUN=Function, var = 2)

しかし、明らかにこの関数は機能しません。まず、この関数を実行すると、が得られError in math_fun(x) : object 'x' not foundます。

第二に、関数が機能したとしても、変数はxであると想定していますが、ユーザーは任意の文字を使用できます。

この2番目の問題の場合、考えられる解決策の1つは、変数として使用する文字を指定するようにユーザーに依頼することです。

foo <- function(FUN, var, variable){
      math_fun <- function(variable){
           FUN
      }
   curve(math_fun, -5, 5) 
   y = math_func(var)     
   points(x=var, y=y)     
}

しかし、私はこれをどれだけ正確に実装できるかについて途方に暮れています...誰かが私が問題の少なくとも一部を解決するのを手伝ってくれるなら、それは素晴らしいことです。ありがとう!

4

1 に答える 1

6

それよりもはるかに簡単です。function(x) x^2 + xユーザー定義関数の定義には、たとえばの代わりに引数が含まれている必要がありますx^2 + x。次に、直接渡して呼び出すことができます。

foo <- function(math_fun, var){

   curve(math_fun, -5, 5)  #plot the mathematical function
   y = math_fun(var)       #compute the function based on a user provided x value
   points(x=var, y=y)      #plot the value from the last step.
}

#A user can use the function defined above in a way as shown below:
Function <- function(x) x^2 + x
foo(Function, var = 2)
于 2013-01-25T21:34:25.177 に答える