Attribute variable name to a named vector

r

Solution

For a one-line solution, use `setNames()`:

nvec <- setNames(num, cID)
nvec
# x1 
# 1 

For an example in which `setName()` supplied a clean and elegant solution to a tricky problem, see @hadley's answer to this question.

Problem

I have a string and and a number ``` cID = 'x1' num = 1 ``` I want to create a named vector ``` nvec = c(x1 = num) ``` but when I do the following, R interprets `cID` as `'cID'` and not as `'x1'`. ``` nvec = c(cID = num) ```

Original source

Related problems