Skip to content

nls() syntax

5 messages · Rolf Turner, Gabor Grothendieck, Duncan Murdoch +1 more

#
I want to fit a model y = x/(x-a) where the value of a depends
on the level of a factor z.  I cannot figure out an appropriate
syntax for nls().  The "parameter" a (to be estimated) should be a
vector of length equal to the number of levels of z.

I tried:

strt <- rep(3,length(levels(z))
names(strt=levels(z)
fit <- nls(y ~ x/(x - a[z]),start=strt,data=xxx)

but of course got an error:
I keep thinking that there is something obvious that I should
be doing, but I can't work out what it is.

Does there *exist* an appropriate syntax for doing what I want
to do?  Can anyone enlighten me?  The data set "xxx" is given
in dput() form at the end of this message.

cheers,

Rolf Turner
#
The start= argument should be as follows:

 nls(y ~ x/(x - a[z]),start=list(a = strt),data=xxx)
On Fri, Dec 11, 2020 at 6:51 PM Rolf Turner <r.turner at auckland.ac.nz> wrote:

  
    
#
On 11/12/2020 6:50 p.m., Rolf Turner wrote:
I don't know of anything easy here.  I think you need to do some tricky 
stuff with formulas to get what you want.  For example,

pred <- function(x, z, ...) {
   a <- unlist(list(...))
   names(a) <- levels(xxx$z)
   x/(x-a[z])
}
strt <- rep(3,length(levels(xxx$z)))
names(strt) <- levels(xxx$z)
fla <- y ~ pred(x, z)
fla[[3]] <- as.call(c(as.list(fla[[3]]), lapply(levels(xxx$z), as.name)))
fit <- nls(fla,start=strt,data=xxx)

That line starting fla[[3]] is the ugly part:  it takes the simple 
formula y ~ pred(x, z) and changes it to y ~ pred(x, z, a1, a2, a3, a4, 
a5).  As far as I know, nls() can't handle vector paramters, it only 
deals with scalars, so this passes them each as a separate argument.

Maybe rlang or one of the other packages like that has code to make this 
less obscure.
#
On Fri, 11 Dec 2020 19:20:26 -0500
Gabor Grothendieck <ggrothendieck at gmail.com> wrote:

            
Nya-ha!  I, uh, clearly wasn't thinking clearly!  (Feel a bit *duh*
now!)

Thanks Gabor.

cheers,

Rolf
#
Hi Rolf,

It might also be worth experimenting to see if

y ~ 1 / ( 1 - a[z]/x )

yields the same result. It might be cleaner if x appears only once in the expression.

Cheers,

Andrew

--
Andrew Robinson
Director, CEBRA; Professor of Biosecurity
School of BioSciences
University of Melbourne, VIC 3010 Australia
Tel: (+61) 0403 138 955
Email: apro at unimelb.edu.au
Website: http://cebra.unimelb.edu.au/

I acknowledge the traditional owners of the land I inhabit and pay my respects to their elders.