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?
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:
## # 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(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(~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?
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)
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.