Search code examples
rlistdplyrpurrrreadr

Create a list from Tibble Columns


I have a tibble like this:

> library(tidyverse)
> tbl <- tibble(x = c('a', 'b', 'c'), y = 1:3)
> tbl
# A tibble: 3 x 2
      x     y
  <chr> <int>
1     a     1
2     b     2
3     c     3

I would like to create a list where the names of the elements of the list are those from x (I have all distinct entries) and the values are those from y. I would like this list:

list(a = 1, b = 2, c = 3)
$a
[1] 1

$b
[1] 2

$c
[1] 3

Thank you in advance


Solution

  • You can convert column y to a list, and setNames with column x:

    setNames(as.list(tbl$y), tbl$x)
    
    #$a
    #[1] 1
    
    #$b
    #[1] 2
    
    #$c
    #[1] 3