Reputation: 3158
I'm trying to get purrr::pmap
work on a formula and i'm missing something obvious.
library(plyr)
library(tidyverse)
library(broom)
This is just a container, where I'll keep track of the separate data frames
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
)
Now I want to map over these three lists
pmap(
list(
d1$vs,
d1$am,
d1$mods
),
~..3 %>%
mutate(vs = ..1,
am = ..2)
)
returns this error:
Error in mutate_impl(.data, dots) : Binding not found: ..1.
Upvotes: 1
Views: 193
Reputation: 3321
If your goal is to have the lm
summaries next to each vs
and am
combo, would this do?
# 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
```
Created on 2018-09-16 by the reprex package (v0.2.0).
Upvotes: 0
Reputation: 24252
Use plyr::mutate
inside 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)
)
The output is:
[[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
Upvotes: 1