列表列数据框中的 purrr pmap
purrr pmap in list-columns data frame
当我有一个包含两个输入列(a 和 b)的列表列数据框 (df1) 时,我可以使用 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))
现在假设我有一个包含 3 个输入列(a、b 和 c)的新数据框 (df2)。
d3 <- mtcars %>% slice(21:10) %>% group_by(cyl) %>% nest(.key = "c")
df2 <- d1 %>% left_join(d2) %>% left_join(d3)
如何使用 3 个输入列获取新列?由于没有map3,我想我应该使用pmap,但我不知道如何。
正如@Sathish 评论的那样,pmap
可以使用,这可以在 mutate
中使用,方法是将列放在 list
中,然后应用函数
library(tidyverse)
df2 %>%
mutate(z = pmap(list(a, b, c), bind_rows))
当我有一个包含两个输入列(a 和 b)的列表列数据框 (df1) 时,我可以使用 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))
现在假设我有一个包含 3 个输入列(a、b 和 c)的新数据框 (df2)。
d3 <- mtcars %>% slice(21:10) %>% group_by(cyl) %>% nest(.key = "c")
df2 <- d1 %>% left_join(d2) %>% left_join(d3)
如何使用 3 个输入列获取新列?由于没有map3,我想我应该使用pmap,但我不知道如何。
正如@Sathish 评论的那样,pmap
可以使用,这可以在 mutate
中使用,方法是将列放在 list
中,然后应用函数
library(tidyverse)
df2 %>%
mutate(z = pmap(list(a, b, c), bind_rows))