我试图让purrr::pmap
处理一个公式并且我错过了一些明显的东西。
library(plyr)
library(tidyverse)
library(broom)
这只是一个容器,我将跟踪单独的数据框
d1 <- expand.grid(vs = c(0, 1),
am = c(0, 1))
d1$mods <- 1:4 %>%
map(function(i)
lm(mpg ~ wt,
data = mtcars %>%
filter(vs == d1$vs[[i]],
am == d1$am[[i]]
)
) %>%
tidy
)
现在我想映射这三个列表
pmap(
list(
d1$vs,
d1$am,
d1$mods
),
~..3 %>%
mutate(vs = ..1,
am = ..2)
)
返回此错误:
Error in mutate_impl(.data, dots) : Binding not found: ..1.
答案 0 :(得分:1)
在plyr::mutate
内使用pmap
:
library(broom)
library(tidyverse)
d1 <- expand.grid(vs = c(0, 1), am = c(0, 1))
d1$mods <- 1:4 %>%
map(function(i)
lm(mpg ~ wt,
data = mtcars %>%
filter(vs == d1$vs[[i]],
am == d1$am[[i]]
)
) %>%
tidy
)
pmap(
list(d1$vs, d1$am, d1$mods),
~..3 %>%
plyr::mutate(vs = ..1, am = ..2)
)
输出结果为:
[[1]]
term estimate std.error statistic p.value vs am
1 (Intercept) 25.059424 3.5111642 7.137070 3.152928e-05 0 0
2 wt -2.438894 0.8421098 -2.896171 1.593780e-02 0 0
[[2]]
term estimate std.error statistic p.value vs am
1 (Intercept) 31.527152 8.976986 3.511998 0.01706422 1 0
2 wt -3.376121 2.796159 -1.207414 0.28126767 1 0
[[3]]
term estimate std.error statistic p.value vs am
1 (Intercept) 42.36357 3.300961 12.833707 0.0002125032 0 1
2 wt -7.91376 1.141476 -6.932921 0.0022726287 0 1
[[4]]
term estimate std.error statistic p.value vs am
1 (Intercept) 44.126436 6.956785 6.342935 0.001437588 1 1
2 wt -7.767647 3.362709 -2.309937 0.068912660 1 1
答案 1 :(得分:0)
如果您的目标是在每个lm
和vs
组合旁边添加am
摘要,这会吗?
# Libraries
library(broom)
library(tidyverse)
#Data
d1 <- expand.grid(vs = c(0, 1), am = c(0, 1))
d1 %>%
mutate(data = pmap(list(vs, am), ~ (lm(mpg ~ wt,
data = (mtcars %>%
filter(vs %in% .x,
am %in% .y))) %>%
tidy()))) %>%
unnest()
#> vs am term estimate std.error statistic p.value
#> 1 0 0 (Intercept) 25.059424 3.5111642 7.137070 3.152928e-05
#> 2 0 0 wt -2.438894 0.8421098 -2.896171 1.593780e-02
#> 3 1 0 (Intercept) 31.527152 8.9769855 3.511998 1.706422e-02
#> 4 1 0 wt -3.376121 2.7961588 -1.207414 2.812677e-01
#> 5 0 1 (Intercept) 42.363570 3.3009614 12.833707 2.125032e-04
#> 6 0 1 wt -7.913760 1.1414756 -6.932921 2.272629e-03
#> 7 1 1 (Intercept) 44.126436 6.9567852 6.342935 1.437588e-03
#> 8 1 1 wt -7.767647 3.3627090 -2.309937 6.891266e-02
```
由reprex package(v0.2.0)于2018-09-16创建。