[R] Problem with logarithmic nonlinear model using nls() from the `stats' package

Gabor Grothendieck ggrothendieck at gmail.com
Sat Oct 1 15:41:51 CEST 2011


On Sat, Oct 1, 2011 at 9:27 AM, Gabor Grothendieck
<ggrothendieck at gmail.com> wrote:
> On Sat, Oct 1, 2011 at 5:28 AM, Casper Ti. Vector
> <caspervector at gmail.com> wrote:
>> Example:
>>
>>> f <- function(x) { 1 + 2 * log(1 + 3 * x) + rnorm(1, sd = 0.5) }
>>> y <- f(x <- c(1 : 10)); y
>>  [1] 4.503841 5.623073 6.336423 6.861151 7.276430 7.620131 7.913338 8.169004
>>  [9] 8.395662 8.599227
>>> nls(x ~ a + b * log(1 + c * x), start = list(a = 1, b = 2, c = 3), trace = TRUE)
>> 37.22954 :  1 2 3
>> Error in numericDeriv(form[[3L]], names(ind), env) :
>>  Missing value or an infinity produced when evaluating the model
>> In addition: Warning message:
>> In log(1 + c * x) : NaNs produced
>>
>> What's wrong here? Am I handling this problem in the wrong way?
>> Any suggestions are welcome, thanks :)
>>
>
> Its linear given c so calculate the residual sum of squares using lm
> (or lm.fit which is faster) given c and optimize over c:
>
> set.seed(123) # for reproducibility
>
> # test data
> x <- 1:10
> y <- 1 + 2 * log(1 + 3 * x) + rnorm(1, sd = 0.5)
>
> # calculate residual sum of squares for best fit given c
> fitc <- function(c) lm.fit(cbind(1, log(1 + c * x)), y)
> rssvals <- function(c) sum(resid(fitc(c))^2)
>
> out <- optimize(rssvals, c(0.01, 10))
>
> which gives:
>
>> setNames(c(coef(fitc(out$minimum)), out$minimum), letters[1:3])
>        a         b         c
> 0.7197666 2.0000007 2.9999899

Also you probably intended to write 10 instead of 1 as the arg to rnorm.


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list