当nls模型无法拟合数据时如何返回NA?

问题描述 投票:0回答:1

我正在应用分组

nlsLM
模型并对其进行求解,以获取每个组的 y 分别最高时的 x 值。但有些研究给出了以下错误

mutate()
中的错误: ℹ 在争论中:
model = map(data, ~nlsLM(y ~ SSlinp(x, a, b, xs), data = .x))
。 由
map()
中的错误引起: ℹ 索引:2。 由
nlsModel()
中的错误引起: !初始参数估计时的奇异梯度矩阵

如何避免这些研究并运行那些可以运行

nlsLM
模型的研究?

这是我使用示例数据的代码

library(tidyverse)
library(gslnls)
library(broom)
library(minpack.lm)
library(nlraa)

df %>%
  nest(data = -SN) %>%
  mutate(model = map(data, ~ nlsLM(y ~ SSlinp(x, a, b, xs), data = .x))) %>% 
  mutate(x_opt = map(model, tidy)) %>%
  unnest(x_opt) %>% 
  filter(term %in% "xs") %>% 
  mutate(y_opt = unlist(map2(estimate, model, ~predict(.y, list(x = .x))))) %>%
  select(SN, estimate, y_opt)

数据

df = structure(list(SN = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 
3L, 3L, 3L, 3L, 3L), x = c(0L, 60L, 90L, 120L, 150L, 0L, 60L, 
90L, 120L, 150L, 0L, 60L, 90L, 120L, 150L), y = c(3569.5, 6698.1, 
6595.2, 6834.4, 6966.7, 3649.7, 4895.1, 5162, 4443.5, 5038.9, 
4097.7, 5664.9, 5518.1, 7608.1, 8081.6)), class = "data.frame", row.names = c(NA, 
-15L))
r tidyverse nls
1个回答
0
投票

这是一个笨拙的、部分的解决方案。您必须添加一个类似的

my_predict
函数,如果模型不好,它将返回正确的 null/
NA
结果。

或者,您可以在模型拟合阶段之后中断管道并删除不起作用的模型(例如

filter(!inherits(model, "try-error"))
或类似的模型),然后运行
tidy
/
predict
,而无需对剩余元素造成麻烦...

empty <- tibble(
    term = c("a", "b", "xs"),
    estimate = NA_real_,
    std.error = NA_real_,
    p.value = NA_real_
)
my_tidy <- function(m) {
    if (inherits(m, "try-error")) empty else broom::tidy(m)
}

df %>%
  nest(data = -SN) %>%
    mutate(model = map(data, ~ try(nlsLM(y ~ SSlinp(x, a, b, xs), data = .x)))) %>% 
    mutate(x_opt = map(model, my_tidy)) %>%
    unnest(x_opt) %>%
    filter(term %in% "xs")
© www.soinside.com 2019 - 2024. All rights reserved.