4
votes

When I have a list-column data frame (df1) with two input columns (a and b), I can obtain a new column using map2

d1 <- mtcars %>% slice(1:10) %>% group_by(cyl) %>% nest(.key = "a")
d2 <- mtcars %>% slice(11:20) %>% group_by(cyl) %>% nest(.key = "b")
df1 <- d1 %>% left_join(d2) 

my_fun <- function(a, b) {
  # some manipulations that involve the dataframe a and b and result in 
  # another dataframe
  # below, just a trivial manipulation 
  a %>% bind_rows(b)  
}

df1 %>% mutate(z = map2(a, b, my_fun)) 

Let´s suppose now that I have a new data frame (df2) with 3 input columns (a, b and c).

d3 <- mtcars %>% slice(21:10) %>% group_by(cyl) %>% nest(.key = "c")
df2 <- d1 %>% left_join(d2) %>% left_join(d3)

How can I obtain a new column using the 3 input columns? As there is not map3, I guess I should be using pmap, but I don't know how.

1
pmap(df[, 1:3], my_fun). Your function has to accept three or more arguments. Please try examples in the help page ?pmapSathish
Try df2 %>% mutate(z = pmap(list(a, b, c), bind_rows))akrun

1 Answers

4
votes

As @Sathish commented pmap can be used and this can be used within mutate by placing the columns in a list and then apply the function

library(tidyverse)
df2 %>% 
   mutate(z = pmap(list(a, b, c), bind_rows))