[R] 'nls' and its arguments
Timur Elzhov
Timur.Elzhov at jinr.ru
Thu Oct 30 15:54:51 CET 2003
Dear R experts!
I'd to fit data by 'nls' with me-supplied function 'fcn'.
1) I'd like 'fcn' to accept arbitrary arguments, i.e. I defined it
as f(...) {<body>}. (Ok, that's not actually impotant).
2) Second, I would NOT like to supply every parameter in the formula.
To illustrate this, let's look at the last example of 'nls' help
page:
## weighted nonlinear regression
data(Puromycin)
Treated <- Puromycin[Puromycin$state == "treated", ]
weighted.MM <- function(resp, conc, Vm, K)
{
## Purpose: exactly as white book p.451 -- RHS for nls()
## Weighted version of Michaelis-Menten model
## ---------------------------------------------------------------
## Arguments: `y', `x' and the two parameters (see book)
## ---------------------------------------------------------------
## Author: Martin Maechler, Date: 23 Mar 2001, 18:48
print(resp)
pred <- (Vm * conc)/(K + conc)
(resp - pred) / sqrt(pred)
}
Pur.wt <- nls( ~ weighted.MM(rate, conc, Vm, K), data = Treated,
start = list(Vm = 200, K = 0.1))
So, in this example I wouldn't like to write `weighted.MM(rate, conc, Vm, K'),
and `start = list(Vm = 200, K = 0.1)', instead I'd like to supply _lists_.
With the 'start' parameter it's easy - I create list
p.start <- list(Vm = 200, K = 0.1)
and assign it to 'start' in nls():
start = p.start
- that works. But, with the formula it's not so simple. Well, I tried
at first to make formula more "list-like":
Pur.wt <- nls( ~ do.call("weighted.MM", list(rate, conc, Vm, K)),
data = Treated,
start = p.start)
- that works too. Now, let's try to separate data and parameters:
Pur.wt <- nls( ~ do.call("weighted.MM", c(list(rate, conc), list(Vm, K))),
data = Treated,
start = p.start)
- that's right. So, I have a data 'Treated', and a start params list
'p.start'. Now, here is the _point_: I want nls to read names of
variables from the lists and supply it to function in the formula.
In this example 'weighted.MM' has a certain arg list, but my function is
'fcn(...)', and I want supply _all_ these names to the fcn. I tried to
change 'list(Vm, K)' to list(as.name("Vm"), as.name("K")):
Pur.wt <- nls( ~ do.call("weighted.MM", c(list(rate, conc), list(as.name("Vm"), as.name("K")))),
data = Treated, start = p.start)
- works again! Now,
p.arg <- list(as.name("Vm"), as.name("K"))
Pur.wt <- nls( ~ do.call("weighted.MM", c(list(rate, conc), p.arg)),
data = Treated, start = p.start)
Error in model.frame(formula, rownames, variables, varnames, extras, extranames, :
invalid variable type
How can I fix this, and supply _lists_ with parameter names (and data names)
to fcn(...) in nls?
Thanks a lot! :-)
--
WBR,
Timur.
More information about the R-help
mailing list