将 lm 与 map2 一起应用

Applying lm with map2

我正在努力学习 purrr's map functions by using map2 to apply lm. Using a subset of the mtcars data set, I create a data frame with combinations of the variables' 个名字,像这样:

# Load libraries
library(dplyr)
library(purrr)

# Subset data
df <- mtcars %>% select(mpg:qsec) 

# Get variable names
car_vars <- colnames(df)

# Create data frame of variable names
foo <- combn(car_vars, 2) %>% t %>% data.frame

# > head(foo)
#    X1   X2
# 1 mpg  cyl
# 2 mpg disp
# 3 mpg   hp
# 4 mpg drat
# 5 mpg   wt
# 6 mpg qsec

接下来,我有一个采用两个变量名称并拟合线性模型的函​​数:

# Fit model
fit_lm <- function(c1, c2){
  lm(paste(c1, c2, sep = "~"), data = df)
} 

我可以像这样用 map2 应用它:

# Fit all the models 
map2(foo$X1, foo$X2, fit_lm)

给出 lm 个对象的列表,打印时看起来像这样:

# [[1]]
# 
# Call:
#   lm(formula = paste(c1, c2, sep = "~"), data = df)
# 
# Coefficients:
#   (Intercept)          cyl  
# 37.885       -2.876  

太棒了!现在,这就是我绊倒的地方。我想将这些 lm 对象添加为我的数据框中的一列,这样我就可以方便地将变量名称与模型本身放在同一行中。所以,我使用 dplyrmutatemap2.

# Not so successful
foo %>% mutate(mods = map2(X1, X2, fit_lm))

生成的 mods 列具有 class NULL 而不是 lm,看起来有点像 lm 对象的 dput,这与我之前的不同(成功的)尝试。显然,我误解了 map2 的工作原理。有人可以解释我的错误吗?

就结果本身而言,你做的很好:

foo <- foo %>% mutate(mods = map2(X1, X2, fit_lm))
str(foo, max.level = 1)
# 'data.frame': 21 obs. of  3 variables:
#  $ X1  : Factor w/ 6 levels "cyl","disp","drat",..: 5 5 5 5 5 5 1 1 1 1 ...
#  $ X2  : Factor w/ 6 levels "cyl","disp","drat",..: 1 2 4 3 6 5 2 4 3 6 ...
#  $ mods:List of 21

问题很简单

class(foo)
# [1] "data.frame"

lm class 这样的复杂列表用 print.data.frame 打印得非常糟糕。因此,为了更好地查看 print.tbl 的结果,我们只需要将 foo 转换为 tibble:

foo <- as.tbl(foo)
foo
# A tibble: 21 x 3
#    X1    X2    mods    
#    <fct> <fct> <list>  
#  1 mpg   cyl   <S3: lm>
#  2 mpg   disp  <S3: lm>
#  3 mpg   hp    <S3: lm>
#  4 mpg   drat  <S3: lm>
#  5 mpg   wt    <S3: lm>
#  6 mpg   qsec  <S3: lm>
#  7 cyl   disp  <S3: lm>
#  8 cyl   hp    <S3: lm>
#  9 cyl   drat  <S3: lm>
# 10 cyl   wt    <S3: lm>
# … with 11 more rows