从map()调用连接data.frames列表

时间:2016-12-14 16:21:46

标签: r dplyr purrr tidyverse

是否有“tidyverse”方式加入data.frames列表(la full_join(),但是> 2 data.frames)?调用map()后,我有一个data.frames列表。我曾经使用Reduce()做过这样的事情,但是想把它们合并为管道的一部分 - 只是没有找到一种优雅的方法来做到这一点。玩具示例:

library(tidyverse)

## Function to make a data.frame with an ID column and a random variable column with mean = df_mean
make.df <- function(df_mean){
  data.frame(id = 1:50,
             x = rnorm(n = 50, mean = df_mean))
}

## What I'd love:
my.dfs <- map(c(5, 10, 15), make.df) #%>%
  # <<some magical function that will full_join() on a list of data frames?>>

## Gives me the result I want, but inelegant
my.dfs.joined <- full_join(my.dfs[[1]], my.dfs[[2]], by = 'id') %>%
  full_join(my.dfs[[3]], by = 'id')

## Kind of what I want, but I want to merge, not bind
my.dfs.bound <- map(c(5, 10, 15), make.df) %>%
  bind_cols()

1 个答案:

答案 0 :(得分:6)

我们可以使用Reduce

set.seed(24)
r1 <- map(c(5, 10, 15), make.df)  %>% 
           Reduce(function(...) full_join(..., by = "id"), .)

或者可以使用reduce

完成此操作
library(purrr)
set.seed(24)
r2 <- map(c(5, 10, 15), make.df)  %>%
             reduce(full_join, by = "id")

identical(r1, r2)
#[1] TRUE