简体   繁体   中英

purrr pmap in list-columns data frame

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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM