Transform a nested list into a tibble or a list of objects according to a specification.
Arguments
- x
(
list) A nested list.- spec
(
tspec) A specification of how to convertx. Generated withtspec_df(),tspec_row(),tspec_object(),tspec_recursive(), orguess_tspec(). IfspecisNULL(the default),guess_tspec(x, inform_unspecified = TRUE)will be used to guess thespec.- unspecified
(
character(1)) What to do withtib_unspecified()fields. Can be one of"error": Throw an error."inform": Inform the user then parse as withtib_variant()."drop": Do not parse these fields."list": Parse unspecified fields into lists as withtib_variant().
Details
Fields specifically tagged as tib_unspecified() in the spec (or guessed
as such) will be handled according to the unspecified argument. Fields that
are present in x but not mentioned in the spec are ignored.
See also
Use untibblify() to undo the result of tibblify().
Examples
# List of Objects -----------------------------------------------------------
x <- list(
list(id = 1, name = "Tyrion Lannister"),
list(id = 2, name = "Victarion Greyjoy")
)
tibblify(x)
#> # A tibble: 2 × 2
#> id name
#> <dbl> <chr>
#> 1 1 Tyrion Lannister
#> 2 2 Victarion Greyjoy
# Provide a specification
spec <- tspec_df(
id = tib_int("id"),
name = tib_chr("name")
)
tibblify(x, spec)
#> # A tibble: 2 × 2
#> id name
#> <int> <chr>
#> 1 1 Tyrion Lannister
#> 2 2 Victarion Greyjoy
# Object --------------------------------------------------------------------
# Provide a specification for a single object
tibblify(x[[1]], tspec_object(spec))
#> $id
#> [1] 1
#>
#> $name
#> [1] "Tyrion Lannister"
#>
# Recursive Trees -----------------------------------------------------------
x <- list(
list(
id = 1,
name = "a",
children = list(
list(id = 11, name = "aa"),
list(id = 12, name = "ab", children = list(
list(id = 121, name = "aba")
))
))
)
spec <- tspec_recursive(
tib_int("id"),
tib_chr("name"),
.children = "children"
)
out <- tibblify(x, spec)
out
#> # A tibble: 1 × 3
#> id name children
#> <int> <chr> <list>
#> 1 1 a <tibble [2 × 3]>
out$children
#> [[1]]
#> # A tibble: 2 × 3
#> id name children
#> <int> <chr> <list>
#> 1 11 aa <NULL>
#> 2 12 ab <tibble [1 × 3]>
#>
out$children[[1]]$children[[2]]
#> # A tibble: 1 × 3
#> id name children
#> <int> <chr> <list>
#> 1 121 aba <NULL>