R:使用 purrr::pmap_df 同时将原始数据帧保留在单个管道中

R: Use purrr::pmap_df while keeping original data frame in a single pipe

我想在我创建的 data.frame 上使用 purrr:pmap_df,然后还给我另一个 data.frame。但是,我希望在单个管道中将原始 data.frame "kept" 和 cbind 编辑到新的 data.frame。示例:

f <- function(a, b, c) {
  return(list(d = 1, e = 2, f = 3))
}

tibble(a = 1:2, b = 3:4, c = 5:6) %>%
  pmap_df(f)

这会给我:

# A tibble: 2 × 3
  d     e     f
<dbl> <dbl> <dbl>
1     1     2     3
2     1     2     3

但我想保留 tibble:

# A tibble: 2 × 6
  a     b     c     d     e     f
<int> <int> <int> <dbl> <dbl> <dbl>
1     1     3     5     1     2     3
2     2     4     6     1     2     3

(愚蠢的例子,但你明白我的意思)。在单个管道中执行此操作的任何优雅方法?

如果你不想重新定义函数,最简单的方法是只在结果上使用 bind_cols,使用 . 将 data.frame 放在你需要的地方:

library(tidyverse)

f <- function(a, b, c) {
    return(list(d = 1, e = 2, f = 3))
}

tibble(a = 1:2, b = 3:4, c = 5:6) %>%
    bind_cols(pmap_df(., f))
#> # A tibble: 2 x 6
#>       a     b     c     d     e     f
#>   <int> <int> <int> <dbl> <dbl> <dbl>
#> 1     1     3     5     1     2     3
#> 2     2     4     6     1     2     3

您还可以使用 ... 表示 pmap 的输入,这样您就可以

tibble(a = 1:2, b = 3:4, c = 5:6) %>% pmap_df(~c(..., f(...)))

哪个returns一样。