过去,我使用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)
)
不是故意的,还是我不知道该怎么做?
答案 0 :(得分: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
的模型。
答案 1 :(得分: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
# ...