[英]How to create a list-column with tibble::tribble()?
When building a tibble from scratch using tribble()
, how can I set up a column as a "list-column" so it could include data of different classes?使用
tribble()
从头开始构建 tibble 时,如何将列设置为“列表列”,以便它可以包含不同类的数据?
For example, consider the following code where I have one logical value and one numeric value.例如,考虑以下代码,其中我有一个逻辑值和一个数值。
library(tibble)
some_numeric <- 5
some_logical <- TRUE
my_df <-
tribble(~name, ~value,
"logical", some_logical,
"numeric", some_numeric)
Whereas I was expecting my_df
to look like:而我期待
my_df
看起来像:
## # A tibble: 2 x 2
## name value
## <chr> <list>
## 1 logical <lgl [1]>
## 2 numeric <dbl [1]>
I actually got this:我实际上得到了这个:
## # A tibble: 2 x 2
## name value
## <chr> <dbl>
## 1 logical 1
## 2 numeric 5
Sure, there's this way using tibble()
that works:当然,有这样一种使用
tibble()
的方法:
tibble(name = c("logical", "numeric"),
value = list(some_logical, some_numeric))
## # A tibble: 2 x 2
## name value
## <chr> <list>
## 1 logical <lgl [1]>
## 2 numeric <dbl [1]>
But I wanted to create it row-wise using tribble()
, and the following doesn't work either:但我想使用
tribble()
逐行创建它,以下也不起作用:
tribble(~name, ~value,
"logical", list(some_logical),
"numeric", list(some_numeric))
## # A tibble: 2 x 2
## name value
## <chr> <list>
## 1 logical <list [1]> ## <--- I don't want nested list but nested *logical* vec
## 2 numeric <list [1]> ## <--- I don't want nested list but nested *double* vec
So my question is, is there a simple way to use tribble()
to set up a list-column in which each value is a nested vector and not a nested list?所以我的问题是,有没有一种简单的方法可以使用
tribble()
来设置一个列表列,其中每个值都是嵌套向量而不是嵌套列表?
library(tidyverse)
f <- tribble(~name, ~value,
"logical", as.vector("some_logical", mode = "list"),
"numeric", as.vector("some_logical", mode = "list"))
f
#> # A tibble: 2 x 2
#> name value
#> <chr> <list>
#> 1 logical <list [1]>
#> 2 numeric <list [1]>
f$value
#> [[1]]
#> [[1]][[1]]
#> [1] "some_logical"
#>
#>
#> [[2]]
#> [[2]][[1]]
#> [1] "some_logical"
Created on 2021-02-22 by the reprex package (v1.0.0)由代表 package (v1.0.0) 于 2021 年 2 月 22 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.