Skip to content

How to define specially nested functions

4 messages · Jerome Asselin, Petr Savicky, Chee Chen

#
On Thu, 2011-04-28 at 23:08 -0400, Chee Chen wrote:
Interesting exercise.

I've got this function, which I think it's doing what you're asking.

f <- function(x,y,z)
{
	fcall <- match.call()
	fargs <- NULL
	if(fcall$x == "x")
		fargs <- c(fargs, "x")
	if(fcall$y == "y")
		fargs <- c(fargs, "y")
	if(fcall$z == "z")
		fargs <- c(fargs, "z")
	
	ffunargs <- as.list(fargs)
	names(ffunargs) <- fargs
	
	argslist <- list(fcall)
	ffun <- append(argslist, substitute( x+y + (x^2-z) ), after=0)[[1]]
	as.function(append(ffunargs, ffun))
}

This yields.
function (z = "z") 
3 + 2 + (3^2 - z)
<environment: 0x132fdb8>
[1] 11

I haven't figured out how to get rid of the default argument value shown
here as 'z = "z"'. That doesn't prevent it to work, but it's less
pretty.  If you find a better way, let me know.

HTH,
Jerome
#
On Thu, Apr 28, 2011 at 11:08:23PM -0400, Chee Chen wrote:
If solving the equation for z with given x and y is the
main purpose, then try the following

  f <- function(x,y,z) x+y + (x^2-z)
  uniroot(f, c(0, 10), x=1, y=3)$root
  [1] 5

Hope this helps.

Petr Savicky.