我经常喜欢拟合和检查在 R 数据框中关联两个变量的多个模型。
我可以使用这样的语法来做到这一点:
require(tidyverse)
require(broom)
models <- list(hp ~ exp(cyl), hp ~ cyl)
map_df(models, ~tidy(lm(data=mtcars, formula=.x)))
但我已经习惯了管道语法,并希望能够做到这样:
mtcars %>% map_df(models, ~tidy(lm(data=., formula=.x)))
这清楚地表明我正在“开始”
mtcars
然后对其进行处理以生成我的输出。但该语法不起作用,给出错误 Error: Index 1 must have length 1
.有没有办法写我的
purrr:map()
以我可以用管道的方式运行 mtcars
进入它以获得与上面的工作代码相同的输出? IE。mtcars %>% <<<something>>>
最佳答案
电话/博士:mtcars %>% {map_df(models, function(.x) tidy(lm(data=., formula=.x)))}
或 mtcars %>% map_df(models, ~tidy(lm(..1,..2)), ..2 = .)
您尝试过的解决方案存在 2 个问题。
首先,如果要将点放在不寻常的位置,则需要使用花括号。
library(magrittr)
1 %>% divide_by(2) # 0.5 -> this works
1 %>% divide_by(2,.) # 2 -> this works as well
1 %>% divide_by(2,mean(.,3)) # this doesn't
1 %>% divide_by(.,2,mean(.,3)) # as it's equivalent to this one
1 %>% {divide_by(2,mean(.,3))} # but this one works as it forces all dots to be explicit.
第二个是您不能将点与
~
一起使用以您想要的方式制定,请尝试 map(c(1,2), ~ 3+.)
和 map(c(1,2), ~ 3+.x)
(甚至 map(c(1,2), ~ 3+..1)
),你会看到你得到相同的结果。当您在 ~
中使用点时公式它不再链接到管道功能。确保点被解释为
mtcars
您需要使用旧的 function(x) ...
定义。这有效:
mtcars %>% {map_df(models, function(.x) tidy(lm(data=., formula=.x)))}
最后,作为奖励,这是我想出的,试图找到一个没有花括号的解决方案:
mtcars %>% map(models,lm,.) %>% map_df(tidy)
mtcars %>% map_df(models, ~tidy(lm(..1,..2)), ..2 = .)
关于r - 使用管道语法处理模型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48587951/