Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning a function in a list, from a function
    text
    copied!<p>I searched for this question, but found answers that weren't specific enough.</p> <p>I'm cleaning up old code and I'm trying to make sure that the following is relatively clean, and hoping that it won't bite me on the rear later on.</p> <p>My question is about passing a function through a function. Look at the "y" part of the following plot statement. The <code>goo(df)[[1]](x)</code> thing works, but am I asking for trouble in any way? If so, is there a cleaner way? </p> <p>Also, if the <code>goo()</code> function is called many many times, for instance in a Monte Carlo analysis, will this load up R's internals or possibly cause some type of environment issues?</p> <p>Edit (02/21/2011) --- The following code is just an example. The real function "goo" has a lot of code before it gets to the approxfun() statement.</p> <pre><code>#Build a dataframe df &lt;- data.frame(a=c(1, 2, 3, 4, 5), b=c(4, 3, 1, 2, 6)) #Build a function that passes a function goo &lt;- function(inp.df) { out.fun &lt;- approxfun(x=inp.df$a, y=inp.df$b, yright=max(inp.df$b), method="linear", f=1) list(out.fun, inp.df$a[5], inp.df$b[5]) } #Set up the plot range x &lt;- seq(1, 4.3, 0.01) #Plot the function plot(x, goo(df)[[1]](x), type="l", xlim=c(0, goo(df)[[2]]), ylim=c(0, goo(df)[[3]]), lwd=2, col="red") grid() goo(df) [[1]] function (v) .C("R_approxfun", as.double(x), as.double(y), as.integer(n), xout = as.double(v), as.integer(length(v)), as.integer(method), as.double(yleft), as.double(yright), as.double(f), NAOK = TRUE, PACKAGE = "stats")$xout &lt;environment: 0219d56c&gt; [[2]] [1] 5 [[3]] [1] 6 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload