Search code examples
rdplyrnlstidymodels

nls missing value or infinity produced


I'm trying to model nested data with a Chapman-Richards function like this: https://image.slideserve.com/575351/testing-eichhorn-s-rule35-n.jpg

My original data looks as follows:

structure(list(Site = c(1, 1, 1, 1, 1, 1, 4, 4, 4, 4, 4, 
4), Height = c(2.4, 11.3, 20.5, 27.4, 32, 34.9, 2.45, 7.45, 13.05, 
17.7, 20.75, 22.8), Volume = c(12, 220, 605, 991, 1288, 1495, 
11, 106, 283, 473, 619, 723)), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

I create a growth model:

model <- function(data){
  nls(Volume~ a * (Height^b), data=data, start=c(Volume=200, Height=5,a=1,b=1))
}

When I nest my data to create a model for each nest:

Silver %>% group_by(Site_class) %>% nest() %>% 
  mutate(mod= map(.x=data, model))

I get the following error:

fitting parameters ‘a’, ‘b’ without any variables
Error in numericDeriv(form[[3L]], names(ind), env) : 
  Missing value or an infinity produced when evaluating the model
Called from: numericDeriv(form[[3L]], names(ind), env)

I'm aware there may be very little variation in the data.

If I try alg="plinear", I get the following error:

fitting parameters ‘a’, ‘b’ without any variables
Error in qr.solve(QR.B, cc) : singular matrix 'a' in solve
Called from: qr.solve(QR.B, cc)

I have tried changing it to robustbase::nlrob in case that would perform better.

This changes the error code to:

Error in parse(text = x, keep.source = FALSE) : 
  <text>:2:0: unexpected end of input
1: ~ 
   ^
Called from: parse(text = x, keep.source = FALSE)

Does anyone know what's causing me this issue or how to solve it? Many thanks!


Solution

  • If I understand what nls is doing, it is estimating the values of parameters a and b in your case. Therefore there is no need to have start values for variables Volume and Height. These are simply the values in the dataset. If you remove them from the start argument, the error goes away and you get a model.

    model <- function(data){
      nls(Volume~ a * (Height^b), data=data, start=c(a = 1, b = 1))
    }
      
    df %>% group_by(Site) %>% nest() %>% 
      mutate(mod= map(.x=data, model))