Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading