Search code examples
rdplyrtidyversepurrr

Add a column to a `tibble` that gives it's list position


I have a list of tibbles and I want to add a column to each tibble that represents it's position in a list.

Lets say I have the following:

library(tidyverse)

l <- list(
  tibble(x = 1:3, y = rev(x)),
  tibble(a = 3:1, b = rev(a))
)

Which produces:

> l
[[1]]
# A tibble: 3 x 2
      x     y
  <int> <int>
1     1     3
2     2     2
3     3     1

[[2]]
# A tibble: 3 x 2
      a     b
  <int> <int>
1     3     1
2     2     2
3     1     3

How can I use tidyverse syntax to get out the following:

> l
[[1]]
# A tibble: 3 x 2
      x     y     list_pos
  <int> <int>        <int>
1     1     3            1
2     2     2            1
3     3     1            1

[[2]]
# A tibble: 3 x 2
      a     b     list_pos
  <int> <int>        <int>
1     3     1            2
2     2     2            2
3     1     3            2

Solution

  • A possible solution:

    library(tidyverse)
    
    imap(l, ~ bind_cols(.x, pos = .y))
    
    #> [[1]]
    #> # A tibble: 3 x 3
    #>       x     y   pos
    #>   <int> <int> <int>
    #> 1     1     3     1
    #> 2     2     2     1
    #> 3     3     1     1
    #> 
    #> [[2]]
    #> # A tibble: 3 x 3
    #>       a     b   pos
    #>   <int> <int> <int>
    #> 1     3     1     2
    #> 2     2     2     2
    #> 3     1     3     2