[R] nls() syntax
Duncan Murdoch
murdoch@dunc@n @end|ng |rom gm@||@com
Sat Dec 12 03:25:11 CET 2020
On 11/12/2020 6:50 p.m., Rolf Turner wrote:
>
>
> 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:
>
>> Error in nls(y ~ x/(x - a[z]), start = strt, data = xxx) :
>> parameters without starting value in 'data': a
>
> 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.
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.
More information about the R-help
mailing list