问题描述
我正在尝试使用 purrr::map 制作一个 lm 对象列表.以 mtcars 为例:
I'm trying to make a list of lm object using purrr::map.use mtcars as an example:
vars <- c('hp', 'wt', 'disp')
map(vars, ~lm(mpg~.x, data=mtcars))
错误:model.frame.default(formula = mpg ~ .x, data = mtcars, drop.unused.levels = TRUE) 中的错误:变量长度不同(找到.x")
error: Error in model.frame.default(formula = mpg ~ .x, data = mtcars, drop.unused.levels = TRUE) : variable lengths differ (found for '.x')
我也试过:
map(vars, function(x) {x=sym(x); lm(mpg~!!x, data=mtcars)})
我收到错误消息:
Error in !x : invalid argument type
谁能告诉我我做错了什么?提前致谢.
Can anyone tell what I did wrong? Thanks in advance.
推荐答案
通常的方式是将公式粘贴
作为字符串,通过map
ping 进行转换as.formula
(您不能制作公式向量;它必须是一个列表),然后是 map
lm
.如果您愿意,您可以将它们全部组合到一个调用中,但我更喜欢映射单个函数,这使代码更易于阅读:
The usual way is to paste
together formulas as strings, convert them by map
ping as.formula
(you can't make a vector of formulas; it has to be a list), and then map
lm
. You can combine it all to a single call if you like, but I've come to prefer mapping single functions, which makes code easier to read:
library(purrr)
c('hp', 'wt', 'disp') %>%
paste('mpg ~', .) %>%
map(as.formula) %>%
map(lm, data = mtcars)
#> [[1]]
#>
#> Call:
#> .f(formula = .x[[i]], data = ..1)
#>
#> Coefficients:
#> (Intercept) hp
#> 30.09886 -0.06823
#>
#>
#> [[2]]
#>
#> Call:
#> .f(formula = .x[[i]], data = ..1)
#>
#> Coefficients:
#> (Intercept) wt
#> 37.285 -5.344
#>
#>
#> [[3]]
#>
#> Call:
#> .f(formula = .x[[i]], data = ..1)
#>
#> Coefficients:
#> (Intercept) disp
#> 29.59985 -0.04122
实际上没有必要调用 map(as.formula)
因为 lm
会将其强制转换为公式,但并非所有模型都如此慷慨(例如 mgcv::gam
).
It's actually unnecessary to call map(as.formula)
as lm
will coerce it into a formula, but not all models are so generous (e.g. mgcv::gam
).
这种方法的一个缺点是对象中列出的调用看起来很时髦,但系数告诉你哪个很容易.一个有用的替代方法是将公式作为字符串保存在 data.frame 的一列中,并将模型保存在列表列中,例如
A downside of this approach are that the call listed in the object looks funky, but the coefficients tell you which is which easily enough anyway. A useful alternative is to keep the formula as a string in one column of a data.frame and the model in a list column, e.g.
library(tidyverse)
data_frame(formula = paste('mpg ~', c('hp', 'wt', 'disp')),
model = map(formula, lm, data = mtcars))
#> # A tibble: 3 x 2
#> formula model
#> <chr> <list>
#> 1 mpg ~ hp <S3: lm>
#> 2 mpg ~ wt <S3: lm>
#> 3 mpg ~ disp <S3: lm>
这篇关于将字符向量映射到 r 中的 lm 公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!