How can I create a vector from two others, using one for the labels and one for the values?

Viewed 56

Let's say I have a vector a = c("Label 1", "Label 2") and a vector b = c(1, 2). I was wondering whether there is an elegant way to create a vector c = c("Label 1" = 1, "Label 2" = 2) from these two. Setting c <- c(a = b) unfortunately doesn't do the job - but is there any way to do this with a single line of code?

3 Answers

Use setNames like this. No packages are used.

(The rlang package has a set_names function which is similar and it is imported by purrr.)

setNames(b, a)

giving:

Label 1 Label 2 
      1       2 

The source of setNames is just this:

> setNames
function (object = nm, nm) 
{
    names(object) <- nm
    object
}
<bytecode: 0x000000001044d4b0>
<environment: namespace:stats>

You can change names of b -

names(b) <- a
b

#Label 1 Label 2 
#      1       2 

We may use the names<-

`names<-`(b, a)
Related