【发布时间】:2018-06-20 13:28:16
【问题描述】:
当我有一个包含两个输入列(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,但我不知道如何。
【问题讨论】:
-
pmap(df[, 1:3], my_fun)。您的函数必须接受三个或更多参数。请尝试帮助页面中的示例?pmap -
试试
df2 %>% mutate(z = pmap(list(a, b, c), bind_rows))