我正在尝试为每个df运行不同的模型,并将其全部嵌套后存储在同一df中。
代码示例:
mt<- mtcars %>% group_by(cyl,am) %>% nest() %>%
mutate(formula = "Add separate model for each row in text like mpg~wt for one row, mpg~wt+hp for another etc.")
mt$formula[[1]] <- "mpg~wt"
mt$formula[[2]] <- "mpg~wt+drat"
mt$formula[[3]] <- "mpg~wt+qsec"
mt$formula[[4]] <- "mpg~wt+gear"
mt$formula[[5]] <- "mpg~wt"
mt<- mutate(model = ?)
我们可以map2
用来循环list
“数据”列和“公式”的相应元素,应用lm
并将其分配回新的列“模型”
library(purrr)
mt$model <- vector('list', nrow(mt))
mt$model[1:5] <- map2(mt$data[1:5], mt$formula[1:5], ~ lm(.y, data = .x))
mt
# A tibble: 6 x 5
# Groups: cyl, am [6]
# cyl am data formula model
# <dbl> <dbl> <list> <chr> <lis>
#1 6 1 <tibble [3 × 9]> mpg~wt <lm>
#2 4 1 <tibble [8 × 9]> mpg~wt+drat <lm>
#3 6 0 <tibble [4 × 9]> mpg~wt+qsec <lm>
#4 8 0 <tibble [12 × 9]> mpg~wt+gear <lm>
#5 4 0 <tibble [3 × 9]> mpg~wt <lm>
#6 8 1 <tibble [2 × 9]> Add separate model for each row in text like mpg~wt for one row, mpg~wt+hp for another … <NUL…
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句