Add tbl name to tbl column?

Hello,

how to mutate

list(a = tibble(x1 = 1, x2 = 2), b = tibble(x1 = 3, x2 = 4))

to

list(a = tibble(nm = "a", x1 = 1, x2 = 2), b = tibble(nm = "b", x1 = 3, x2 = 4))

with the same colname,

thanks.

A simple way, using imap() to get the names:

library(tidyverse)

xx <- list(a = tibble(x1 = 1, x2 = 2), b = tibble(x1 = 3, x2 = 4))

xx |>
  imap(~ add_column(.x, nm = .y, .before = 1))
#> $a
#> # A tibble: 1 × 3
#>   nm       x1    x2
#>   <chr> <dbl> <dbl>
#> 1 a         1     2
#> 
#> $b
#> # A tibble: 1 × 3
#>   nm       x1    x2
#>   <chr> <dbl> <dbl>
#> 1 b         3     4

Created on 2023-10-30 with reprex v2.0.2

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.