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
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.