Search code examples
rpurrrrlang

Function that captures the elements of a list and uses them as names to create a list-column data frame


I have the following data frames

d1 <- tibble(condition = c("a", "b"), x = c(1, 1)) %>% group_by(condition)
d2 <- tibble(condition = c("a", "b"), y = c(2, 2)) %>% group_by(condition)
d3 <- tibble(condition = c("a", "b"), z = c(3, 3)) %>% group_by(condition)

and I want to build the data frame d

d1_nest <- d1 %>% nest(.key = d1)
d2_nest <- d2 %>% nest(.key = d2)
d3_nest <- d3 %>% nest(.key = d3)

d <- d1_nest %>% left_join(d2_nest) %>% left_join(d3_nest)

and I would like to do that with a function

my_fun(list(d1, d2, d3))

I started with

my_fun <- function(l) {
 l %>% map(nest)
}

The problem is that I want to supply the name of the data frames (d1, d2 and d3) in the argument .key of nest, but I don't know how to do it.

I guess once I can include the .keyargument, it should be easy to apply left_join using reduce.


Solution

  • You have to map the dfs with their names. One way to do it is map2() but purrr now has imap() that gives default names if not existing. Finally, since .key is a quasiquoted argument, you need to unquote the name.

    my_fun <- function(l) {
     imap(l, function(df, name) nest(df, .key = !!name))
    }