Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute variable name to a named vector

Tags:

r

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)
like image 881
Youcha Avatar asked Jun 25 '12 21:06

Youcha


1 Answers

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.

like image 91
Josh O'Brien Avatar answered Sep 29 '22 08:09

Josh O'Brien