我正试图以更有效的方式使用purrr
包中的map
,我现在正在做的。我有3个不同的数据集,假设iris_1, iris_2和iris_3。
我想对所有3个数据集运行相同的线性回归。我的最终目标是使用map
从这3个回归中获得所有系数.
我的代码是这样的:
library(purrr)
library(dplyr)
library(tidyr)
# Load data
iris <- iris
#-------------------------------------------------------------------------------------------------------------#
#Basic modifications
#-------------------------------------------------------------------------------------------------------------#
iris_1 <- iris %>% dplyr::filter(Species=="versicolor")
iris_2 <- iris %>% dplyr::filter(Species=="virginica")
iris_3 <- iris %>% dplyr::filter(Species=="setosa")
Databases <- list(iris_1,iris_2,iris_3)
####Step A
Linear_Models <- map(Databases, ~ lm(Sepal.Length ~ Sepal.Width + Petal.Length , data = .x))
M_1 <- Linear_Models[[1]]
M_2 <- Linear_Models[[2]]
M_3 <- Linear_Models[[3]]
####Step B
Linear_Models_Coeff <- list(M_1,M_2,M_3)
Coeff <- map(Linear_Models_Coeff, ~ coef(summary(.x)))
C_M_1 <- Coeff[[1]]
C_M_2 <- Coeff[[2]]
C_M_3 <- Coeff[[3]]
我试着用一种更有效的方式来完成前面的步骤(也就是把步骤a和B放在一起),方法如下:然而,当我试图获得系数时,我没有得到我在前面的步骤(i.e. C_M_1 <- Coeff[[1]])
中得到的预期结果。
Linear_Models <- map(Databases, ~ lm(Sepal.Length ~ Sepal.Width + Petal.Length , data = .x),~ coef(summary(.x)))
C_M_1 <- Linear_Models[[1]]
提前感谢!!我知道与purrr
不同的其他包有多种方法可以做到这一点。但是我真的很感激包含purrr
包的帮助。
你可以一次完成(将所有函数都放入map中),例如
purrr::map(Databases, ~ lm(Sepal.Length ~ Sepal.Width + Petal.Length ,
data = .x) %>% summary() %>% coef()) %>%
set_names(c("M1", "M2", "M3"))
结果:
$M1
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.1164314 0.4942556 4.282059 9.063960e-05
Sepal.Width 0.2476422 0.1868389 1.325431 1.914351e-01
Petal.Length 0.7355868 0.1247678 5.895648 3.870715e-07
$M2
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.6247824 0.52486745 1.190362 2.398819e-01
Sepal.Width 0.2599540 0.15333757 1.695305 9.663372e-02
Petal.Length 0.9348189 0.08960197 10.433017 8.009442e-14
$M3
Estimate Std. Error t value Pr(>|t|)
(Intercept) 2.3037382 0.38529423 5.979166 2.894273e-07
Sepal.Width 0.6674162 0.09035581 7.386533 2.125173e-09
Petal.Length 0.2834193 0.19722377 1.437044 1.573296e-0