简体   繁体   English

从标题列创建列表

[英]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. 我想创建一个列表,其中列表元素的名称是x的名称(我有所有不同的条目),值是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 : 您可以将y列转换为列表,并将setNames转换为x

setNames(as.list(tbl$y), tbl$x)

#$a
#[1] 1

#$b
#[1] 2

#$c
#[1] 3

using tidyr 使用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. spread采用长格式的数据并使其变宽,然后将其转换为列表可提供所需的输出。

# $a
# [1] 1
# 
# $b
# [1] 2
# 
# $c
# [1] 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM