Ciaran O Brien
Ciaran O Brien

Reputation: 384

R - NLS Error 'Missing value or an infinity produced when evaluating the model'

I found the following piece of code by a user called Taylor White on a Medium blog which calculates the R0 number. I tried to run the code but get hit with the following error:

Error in numericDeriv(form[[3L]], names(ind), env) : Missing value or an infinity produced when evaluating the model

I found a similar post on stackoverflow (link below) which suggested using minpack.lm but frankly the code there looked unsimilar to my own. There was also a post suggesting to remove 0 values, which I tried but still had no luck progressing.

nls troubles: Missing value or an infinity produced when evaluating the model

I also tried altering the 'start' values which did not help either. Is there any further guidance from anybody? It would be much appreciated.

library(tidyverse)

# Pull in data from John Hopkins
johns_hopkins_cases = read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv') %>%
  pivot_longer(cols = matches('^([0-9])'), names_to = 'date', values_to = 'cases')

# Change column names to lower case and add hyphens
names(johns_hopkins_cases) = names(johns_hopkins_cases) %>% tolower() %>% str_replace('[\\/]', '_')

# Take US data only
us_jh_cases = filter(johns_hopkins_cases, country_region == 'US') %>%
  mutate(date = as.Date(date, format = '%m/%d/%y')) %>%
  arrange(date) %>%
  mutate(
    lag_cases = lag(cases, 1), 
    new_cases = cases - lag_cases,
    new_cases = ifelse(is.na(new_cases), 1, new_cases),
    t = as.numeric(date - min(date))
  )

# Fit a simple exponetial model using non-linear least squares. 
simple_exponential_model = nls(cases ~  case_networks * r0^(t/5), data = us_jh_cases, 
                               start = list(case_networks = 1, r0 = 2.5))

Upvotes: 0

Views: 1839

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270160

Use the plinear algorithm. In that case the right hand side and starting values should omit case_networks and its value will be reported as .lin.

fm <- nls(cases ~  r0^(t/5), data = us_jh_cases, alg = "plinear", 
  start = list(r0 = 2.5))
fm

giving:

Nonlinear regression model
  model: cases ~ r0^(t/5)
   data: us_jh_cases
       r0      .lin 
1.094e+00 1.513e+05 
 residual sum-of-squares: 9.836e+12

Number of iterations to convergence: 10 
Achieved convergence tolerance: 6.719e-06

Graph

plot(cases ~ t, us_jh_cases, pch = ".", cex = 2)
lines(fitted(fm) ~ t, us_jh_cases, col = "red") # fit shown in red

screenshot

Upvotes: 1

Related Questions