Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 356
Tommaso Guerrini Avatar asked Nov 20 '25 09:11

Tommaso Guerrini


2 Answers

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
like image 160
Psidom Avatar answered Nov 22 '25 23:11

Psidom


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
like image 20
Eumenedies Avatar answered Nov 22 '25 21:11

Eumenedies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!