2

我过去曾使用 nlme 来拟合和比较非线性模型。我现在想用它来拟合由多个标识符分组的数据的模型。如果我能集成 dplyr、purrr 和 nlme,那就太好了。其中一件好事是使用 nlme 包中的自启动功能。我也有很多模型要运行。我只是不确定它是否会全部融合在一起。

当前的nlme情况。这有效,但仅限于一个分组变量:

library(tidyverse)
library(nlme)
diamonds_grouped <- groupedData(price ~ carat | cut, data = diamonds)
nlsList(price ~ SSlogis(carat, Asym, xmid, scal), data = diamonds_grouped)  

所需的工作流程。不起作用,我已经走了多远:

fit_mod <- function(df) {  ### Not much faith in how I wrote this function
  nlsList(price ~ SSlogis(carat, Asym, xmid, scal), data = .)
} 

diamonds %>%
group_by(cut, color) %>%
nest() %>%
mutate(
  model = map(data, fit_mod),
  tidied = map(model, tidy)
)

不是故意的,或者我只是不知道该怎么做?

4

2 回答 2

1

您可以修改函数以包含每个子集的分组数据

library(tidyverse)
library(nlme)

fit_mod <- function(df) {  
  diamonds_grouped <- groupedData(price ~ carat | cut, data = df)
  nlsList(price ~ SSlogis(carat, Asym, xmid, scal), data = diamonds_grouped)
} 

然后拆分数据并申请fit_mod每个子集

diamonds %>% group_split(cut, color) %>%  map(fit_mod)

#[[1]]
#Call:
#  Model: price ~ SSlogis(carat, Asym, xmid, scal) | cut 
#   Data: diamonds_grouped 

#Coefficients:
#         Asym     xmid      scal
#Fair 16928.32 1.410986 0.4113035

#Degrees of freedom: 163 total; 160 residual
#Residual standard error: 1449.725

#[[2]]
#Call:
#  Model: price ~ SSlogis(carat, Asym, xmid, scal) | cut 
#   Data: diamonds_grouped 

#Coefficients:
#         Asym     xmid      scal
#Fair 16565.84 1.409934 0.3833443

#Degrees of freedom: 224 total; 221 residual
#Residual standard error: 1175.058
#.....
#.....

另外我认为你不能将tidy函数应用于模型类nlsList

于 2019-11-26T03:42:17.917 回答
1

一种选择是引入一个新变量,该变量捕获跨多个变量的所有可能分组。使用您的示例:

diamonds2 <- diamonds %>% mutate( grp = str_c(cut, "_", color) )
diamonds2_grp  <- groupedData( price ~ carat | grp, data = diamonds2 )
nlsList(price ~ SSlogis(carat, Asym, xmid, scal), data = diamonds2_grp )

# Call:
#   Model: price ~ SSlogis(carat, Asym, xmid, scal) | grp 
#    Data: diamonds2_grp 
# 
# Coefficients:
#                 Asym     xmid      scal
# Fair_E      16565.84 1.409934 0.3833443
# Fair_D      16928.32 1.410986 0.4113035
# Fair_F      13905.28 1.335952 0.3877184
# Good_E      15894.55 1.253196 0.3245564
# Fair_I      17427.69 1.783398 0.5071487
# Good_J      17233.34 1.676204 0.4604250
# ...
于 2019-12-02T15:58:28.817 回答