Convert between column pairs and named vector or lists
as_pairs.Rd
Convert named vectors or nested lists into a two-column table of node pairs and vice versa.
as_pairs_from_named
extracts the vector or list element names and the values, unnesting where necessary.
pairs_to_named_vector
extracts name-value pairs from column pairs as is,
whilst pairs_to_named_list()
nests the values first.
Usage
as_pairs_from_named(x, names_to = "name", values_to = "value")
pairs_to_named_vector(df, names_from = name, values_from = value)
pairs_to_named_list(df, names_from = name, values_from = value)
Arguments
- x
a Named vector or list. Lists values are flattened via
unlist()
.- names_to, values_to
character vector specify the new columns to pass the information in
x
into.- df
a data frame-like object with at least two columns
- names_from, values_from
two columns in
x
to convert to names and values
Functions
as_pairs_from_named()
: Convert named vector or nested list into column pairspairs_to_named_vector()
: Convert column pairs to named vectorpairs_to_named_list()
: Convert column pairs to nested named list
Examples
# Coerce named vectors and list to column pairs
veg_vec <- c(eggplant = "aubergine", zucchini = "courgette")
as_pairs_from_named(veg_vec, "au_eng", "uk_eng")
#> # A tibble: 2 × 2
#> au_eng uk_eng
#> <chr> <chr>
#> 1 eggplant aubergine
#> 2 zucchini courgette
animal_list <- list(
MAMM = c("elephant", "whale", "monkey"),
REPT = c("lizard", "turtle"),
CRUS = c("crab")
)
as_pairs_from_named(animal_list, "class", "animal")
#> # A tibble: 6 × 2
#> class animal
#> <chr> <chr>
#> 1 MAMM elephant
#> 2 MAMM whale
#> 3 MAMM monkey
#> 4 REPT lizard
#> 5 REPT turtle
#> 6 CRUS crab
# Convert pairs back to named vector and lists
veg_from_pairs <- as_pairs_from_named(veg_vec) |>
pairs_to_named_vector(names_from = name, values_from = value)
identical(veg_vec, veg_from_pairs)
#> [1] TRUE
animal_from_pairs <- as_pairs_from_named(animal_list, "class", "animal") |>
pairs_to_named_list(names_from = class, values_from = animal)
identical(animal_list, animal_from_pairs)
#> [1] TRUE