【问题标题】:how to add a column to a netsed tibble in R如何在 R 中将列添加到网状小标题
【发布时间】:2021-02-15 17:14:35
【问题描述】:

我怎么能用 purrr 的地图来转换一个 tibble。
我有以下嵌套的小标题:
 tbl_a <- tibble(
  a = letters[1:3],
  b = 1:3
)

tbl_b <- tibble(
  c = letters[1:3],
  d = 1:3
)

tbl_nested <- tibble(
  name = c("Test", "Sand"),
  nest_tbl = list(tbl_a,tbl_b)
)

最终嵌套的小标题应该是:

tbl_a_new <- tibble(
  name = "Test",
  a = letters[1:3],
  b = 1:3
)

tbl_b_new <- tibble(
  name = "San",
  a = letters[1:3],
  b = 1:3
)

 tibble(
  name = c("Test", "Sand"),
  nest_tbl = list(tbl_a,tbl_b),
  nest_tbl_new = list(tbl_a_new,tbl_b_new)
)


  name  nest_tbl         nest_tbl_new    
  <chr> <list>           <list>          
1 Test  <tibble [3 x 2]> <tibble [3 x 3]>
2 Sand  <tibble [3 x 2]> <tibble [3 x 3]>

非常感谢 为您提供帮助

【问题讨论】:

    标签: r purrr tibble


    【解决方案1】:

    我们可以使用map2

    library(dplyr)
    library(purrr)
    tbl_nested %>%
       mutate(nest_tbl_new = map2(nest_tbl, name, ~ 
              .x %>% 
                mutate(name = .y)))
    

    -输出

    # A tibble: 2 x 3
    #  name  nest_tbl         nest_tbl_new    
    #  <chr> <list>           <list>          
    #1 Test  <tibble [3 × 2]> <tibble [3 × 3]>
    #2 Sand  <tibble [3 × 2]> <tibble [3 × 3]>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 2012-12-10
      相关资源
      最近更新 更多