[R] Passing function arguments

David Winsemius dwinsemius at comcast.net
Fri Feb 11 17:39:52 CET 2011


On Feb 11, 2011, at 6:14 AM, Michael Pearmain wrote:

> Hi All,
>
> Im looking for some help passing function arguments and referencing  
> them,
> I've made a replica, less complicated function to show my problem,  
> and how
> i've made a work around for this. However i suspect there is a _FAR_  
> better
> way of doing this.
>
> If i do:
> BuildDecayModel <- function(x = "this", y = "that", data =  
> model.data) {
>  model <- nls(y ~ SSexp(x, y0, b), data = model.data)
>  return(model)
> }
> ...
>
> "Error in lm.fit(x, y, offset = offset, singular.ok =  
> singular.ok, ...) :
>  0 (non-NA) cases"
>
> This function returns an error because the args are passed as "this"  
> and
> "that" to the model, and so fails (correct?)
>
> If  i do the following:
> BuildDecayModel <- function(x = "total.reach", y = "lift", data =
> model.data) {
>  x <- data[[x]]
>  y <- data[[y]]
>  model.data <- as.data.frame(cbind(x,y))
>  model <- nls(y ~ SSexp(x, y0, b), data = model.data)
>  return(model)
> }
>
> This works for me, but it seems that i'm missing a trick with just
> manipulating the args rather than making an entire new data.frame to  
> work
> off,

The trick you are missing is how to build a formula from component  
character objects. The usual approach something like this:

?formula

Perhaps:
form <- as.formula( paste(y, "~ SSexp(, " , x , ", y0, b)" ) )  
(untested)
model <- nls(form, data = model.data)

paste() should result in evaluation of the argument to return "this"  
and "that" which will then be bundled into a proper language object  
which is not just a character string. I should say I hope this works,  
but there are mysteries regarding the environment of evaluation that  
continue to trip me up.

-- 
David.
>
> Can anyone offer some advice?

(Some further advice: Set your client to post in plain text.)
>
> Thanks in advance
>
> Mike


David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list