3

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

www
  • 38,575
  • 12
  • 48
  • 84
Tommaso Guerrini
  • 1,499
  • 5
  • 17
  • 33

2 Answers2

6

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
Psidom
  • 209,562
  • 33
  • 339
  • 356
5

using tidyr

library(tidyr)
tbl <- tibble(x = c('a', 'b', 'c'), y = 1:3)
as.list(spread(tbl, x, y))

spread takes the long format data and makes it wide, then converting it to a list gives the desired output.

# $a
# [1] 1
# 
# $b
# [1] 2
# 
# $c
# [1] 3
Eumenedies
  • 1,618
  • 9
  • 13
  • 2
    @TommasoGuerrini it's worth noting that my solution throws an error if your `x` are not unique, whereas Psidom's answer will happily have multiple list elements of the same name. Neither is more right or wrong since you didn't specify but, perhaps consider which is right for your situation. Of course, it doesn't matter if you are certain there are no duplicates. – Eumenedies Oct 02 '17 at 13:48
  • I didn't notice having more duplicates, but weirdly I still would need Psidom's answer. Thank you for specifying – Tommaso Guerrini Oct 02 '17 at 13:50