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

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

我在 Medium 博客上找到了一个名为 Taylor White 的用户的以下代码,它计算了 R0 数。我尝试 运行 代码但遇到以下错误:

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

我在 Whosebug(下面的 link)上发现了一个类似的 post,它建议使用 minpack.lm,但坦率地说,那里的代码看起来与我自己的不相似。还有一个 post 建议删除 0 个值,我试过了,但仍然没有进展。

我还尝试更改 'start' 值,但也无济于事。有人有进一步的指导吗?将不胜感激。

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))

使用plinear算法。在这种情况下,右侧和起始值应省略 case_networks,其值将报告为 .lin.

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

给予:

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

图表

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