使用管道语法处理模型列表 [英] working with lists of models using the pipe syntax

查看:75
本文介绍了使用管道语法处理模型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常喜欢拟合并检查与R数据框中的两个变量相关的多个模型。

I often like to fit and examine multiple models that relate two variables in an R dataframe.

我可以使用以下语法来做到这一点:

I can do that using syntax like this:

require(tidyverse)
require(broom)
models <- list(hp ~ exp(cyl), hp ~ cyl)
map_df(models, ~tidy(lm(data=mtcars, formula=.x)))

但是我已经习惯了管道语法,并希望能够实现以下功能:

But I'm used to the pipe syntax and was hoping to be able to something like this:

mtcars %>% map_df(models, ~tidy(lm(data=., formula=.x)))

这清楚表明我是从 mtcars 开始,然后对其进行处理以生成输出。但是该语法不起作用,给出错误错误:索引1的长度必须为1

That makes it clear that I'm "starting" with mtcars and then doing stuff to it to generate my output. But that syntax doesn't work, giving an error Error: Index 1 must have length 1.

是否存在一种写我的 purrr:map()函数的方法,可以将 mtcars 插入该函数以获取与上面的工作代码相同的输出?即

Is there a way to write my purrr:map() function in a way that I can pipe mtcars into it to get the same output as the working code above? I.e.

mtcars %>% <<<something>>>


推荐答案

tl / dr: mtcars %>%{map_df(models,function(.x)tidy(lm(data =。,Formula = .x)))}}

mtcars%>%map_df(models,〜tidy(lm(.. 1,.. 2)),..2 =。)

您尝试过的解决方案有两个问题。

There are 2 problems with the solution you've tried.

首先,如果要将点放置在不寻常的位置,则需要使用花括号。

The first is that you need to use curly braces if you want to place the dot in an unusual place.

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.

第二个是您不能在〜<中使用点/ code>公式,请尝试 map(c(1,2),〜3 +。) map( c(1,2),〜3 + .x)(甚至 map(c(1,2),〜3 + .. 1)),您将看到相同的结果。到您在公式中使用点时,它不再与管道函数链接。

The second is that you can't use the dot with the ~ formulation in the way you intended, try map(c(1,2), ~ 3+.) and map(c(1,2), ~ 3+.x) (or even map(c(1,2), ~ 3+..1)) and you'll see you get the same result. By the time you use the dot in a ~ formula it's not linked to the pipe function anymore.

确保将点解释为 mtcars ,您需要使用旧的 function(x)... 定义。

To make sure the dot is interpreted as mtcars you need to use the good old function(x) ... definition.

这有效:

mtcars %>% {map_df(models, function(.x) tidy(lm(data=., formula=.x)))}

最后,作为奖励,这是我想到的,试图找到没有花括号的解决方案:

Finally, as a bonus, here's what I came up with, trying to find a solution without curly braces :

mtcars %>% map(models,lm,.) %>% map_df(tidy)
mtcars %>% map_df(models, ~tidy(lm(..1,..2)), ..2 = .)

这篇关于使用管道语法处理模型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆