[R] Function call within a function.

Jason Barnhart jasoncbarnhart at msn.com
Fri Jun 29 23:46:16 CEST 2007


[SNIP]

> 
> This has been very helpful though I still do not
> understand why one must call nts$cda using the
> eval(parse()) command.  Is it because nts is created
> within the ukn environment?  

You don't *have* to use the eval(parse()).  This works just as 
well: mysum <- nts$cda.

However, it appeared to me that you wanted the flexibility to return 
different values depending on the function call.

results <- ukn(dd1, "a", "b", "nts$cda")
results2 <- ukn(dd1, "a", "b", "nts$cdb")

The eval/parse allows you to convert text into objects through 
eval().  So the "nam1" argument is specified by the user to return 
the object of choice.

#Here's a simple example of eval/parse that will run
#from the prompt.
t <- "ls()"
t
parse(text=t)
eval(parse(text=t))

I think Dan Nordlund's comment "Functions generally shouldn't 
require knowing how other functions work, they should only rely 
on what value is returned." is more useful here.  Since R 
provides many ways to accomplish the same thing you can avoid 
eval/parse altogether. 

Note that his solution returned a vector of three values where as 
mine returned a list.  It's unclear which you prefer, and it may 
be neither (especially as this was just a simple example).  

In this simple case, I would return a list with named elements 
and expect all objects returned from this function to have the 
same attributes. Then either "cda" or "cdb" could be used as 
necessary.

As an example, consider a plotting function that requires both 
"cda" and "cdb" in order to plot them simultaneously.

[SNIP]



More information about the R-help mailing list