Skip to contents

extract_named() retrieves a vector from an element of a list or data.frame and assigns names extracted from another element.

Usage

extract_named(x, value, name)

Arguments

x

list or data.frame, indexable object containing the elements to extract.

value

character(1) or integer(1), column name or index containing the values for the output vector.

name

character(1) or integer(1), column name or index containing the labels to assign as names.

Value

A vector of the same type as x[[value]], with names attribute set to the elements of x[[name]].

Details

The function relies on the base extraction operator [[ and stats::setNames() to build the named vector without intermediate object copies.

Examples

# From a data.frame
df = data.frame(id = c("a", "b", "c"), score = c(10, 20, 30))
extract_named(df, "score", "id")
#>  a  b  c 
#> 10 20 30 

# From a list
lst = list(val = 1:3, lab = c("x", "y", "z"))
extract_named(lst, 1, 2)
#> x y z 
#> 1 2 3