将列表导入purrr::映射并在.x中使用seq_

将列表导入purrr::映射并在.x中使用seq_,r,dplyr,pipe,purrr,R,Dplyr,Pipe,Purrr,通常我会生成tibble列表,然后我希望通过管道将其转发到purrr::map调用中。我经常想给每个TIBLE添加一个标识符列,然后将它们连接在一起。我正在寻找一种方法,不必为了能够使用seq_添加id列而生成污染全局环境的中间变量 加载库: library(tidyverse) 生成reprex: reprex_list <- list(Aleena = structure(list( name = "Ratts Tyerell", height = 79L, mass = 1

通常我会生成tibble列表,然后我希望通过管道将其转发到
purrr::map
调用中。我经常想给每个TIBLE添加一个标识符列,然后将它们连接在一起。我正在寻找一种方法,不必为了能够使用seq_添加id列而生成污染全局环境的中间变量

加载库:

library(tidyverse)
生成reprex:

reprex_list <- list(Aleena = structure(list(
  name = "Ratts Tyerell", height = 79L,
  mass = 15, hair_color = "none", skin_color = "grey, blue",
  eye_color = "unknown", birth_year = NA_real_, gender = "male",
  homeworld = "Aleen Minor", films = list("The Phantom Menace"),
  vehicles = list(character(0)), starships = list(character(0))
), class = c(
  "tbl_df",
  "tbl", "data.frame"
), row.names = c(NA, -1L)), Besalisk = structure(list(
  name = "Dexter Jettster", height = 198L, mass = 102, hair_color = "none",
  skin_color = "brown", eye_color = "yellow", birth_year = NA_real_,
  gender = "male", homeworld = "Ojom", films = list("Attack of the Clones"),
  vehicles = list(character(0)), starships = list(character(0))
), class = c(
  "tbl_df",
  "tbl", "data.frame"
), row.names = c(NA, -1L)), Cerean = structure(list(
  name = "Ki-Adi-Mundi", height = 198L, mass = 82, hair_color = "white",
  skin_color = "pale", eye_color = "yellow", birth_year = 92,
  gender = "male", homeworld = "Cerea", films = list(c(
    "Attack of the Clones",
    "The Phantom Menace", "Revenge of the Sith"
  )), vehicles = list(
    character(0)
  ), starships = list(character(0))
), class = c(
  "tbl_df",
  "tbl", "data.frame"
), row.names = c(NA, -1L)))

但后者不起作用。显然,这里的额外麻烦是最小的,但有时在生成中间列表之前,我已经有多行代码,然后我必须将其分配给一个单独的变量。然后再次开始管道,我很确定这可以在一个代码块中完成,但我还没有找到一种方法。有什么想法吗?谢谢。

尝试使用
purrr::map\u dfr
并指定
.id
参数:

reprex_list %>% map_dfr(~mutate_all(., as.character), .id='species')
或者最好添加“物种”列,而不做其他操作:

reprex_list %>% map_dfr(identity, .id='species')
编辑:


实际上是实现这一点的最佳方法,根据上面的评论,请尝试使用
purrr::map\u dfr
并指定
.id
参数:

reprex_list %>% map_dfr(~mutate_all(., as.character), .id='species')
或者最好添加“物种”列,而不做其他操作:

reprex_list %>% map_dfr(identity, .id='species')
编辑:


实际上这是最好的方法,正如上面的评论所说,
dplyr::bind_rows(reprex_list,.id=“species”)%%>%tidyr::unnest(films)
接近你想要的吗?
dplyr::bind_rows(reprex_list,.id=“species”)%%>%tidyr::unnest(films)
接近你想要的吗?很接近。。。它取代了
purrr::reduce(full_join)
,这将解决约90%的用例。如果可以在管道的下游使用
.x=seq_along()
,问题就更为复杂了。你可以使用
imap
-我稍后会发布完整的答案,它很接近。。。它取代了
purrr::reduce(full_join)
,这将解决约90%的用例。如果可以在管道下游使用
.x=seq_along()
,问题就更为复杂了。你可以使用
imap
——我稍后会发布完整答案
reprex_list %>% bind_rows(.id = "species")