I want to write a wrapper function around a procedure that involves dplyr::mutate() and purrr::map2().
To demonstrate, consider the following tibble called trb:
df_1 <- mtcars[, c("am", "disp")]
df_2 <- mtcars[, c("mpg", "carb")]
trb <-
tibble::tibble(dat_a = list(df_1),
dat_b = list(df_2))
trb
#> # A tibble: 1 x 2
#> dat_a dat_b
#> <list> <list>
#> 1 <df [32 x 2]> <df [32 x 2]>
I want to mutate another column in trb, called dat_c that will include a data frame with one column from dat_a and one column from dat_b. The following code allows me to achieve it:
library(dplyr)
library(purrr)
output <-
trb %>%
mutate(dat_c = map2(.x = dat_a, .y = dat_b, .f = ~data.frame(my_lovely_am = .x$am,
suberb_carb_col = .y$carb)))
output %>%
pull(dat_c)
#> [[1]]
#> my_lovely_am suberb_carb_col
#> 1 1 4
#> 2 1 4
#> 3 1 1
#> 4 0 1
#> 5 0 2
#> 6 0 1
# I removed the rest of the rows
How can I wrap the mutate() procedure as above inside a custom function? Specifically problematic is when referencing .x$bar and .y$foo. How can I specify those columns names to be taken from an argument of the wrapper function?
What I imagine is a custom function that is built similarly to:
create_dat_c <- function(.trb, colname_dat_a, colname_dat_b, header_a, header_b) {
.trb %>%
mutate(dat_c = map2(.x = dat_a, .y = dat_b, .f = ~data.frame(header_a = .x$colname_dat_a,
header_b = .y$colname_dat_b)))
}
and is called with:
create_dat_c(trb,
colname_dat_a = am,
colname_dat_b = carb,
header_a = "splendid_am",
header_b = "wonderful_carb")
# and returns:
## # A tibble: 1 x 3
## dat_a dat_b dat_c
## <list> <list> <list>
## 1 <df [32 x 2]> <df [32 x 2]> <df [32 x 2]> <<-~-~- dat_c has 2 cols: splendid_am & wonderful_carb
In sum, it is the part of data.frame(header_a = .x$colname_dat_a, header_b = .y$colname_dat_b) that I struggle with. How to make it play well with wrapper's arguments?