How to add named element to vector R named from variable

I want to add an element, say 100, to the vector V and use the value of the variable x as the new element name. I know it can be done like this:

V = c(V, 100)
names(V)[length(V)] = x

      

but I'm looking for a simple one line solution if there is one. I tried:

V = c(V, as.name(x)=100)

      

and

V = c(V, eval(x)=100)

      

but they don't work.

+3


source to share


2 answers


Ronak Shah's answer worked well, but then I discovered an even simpler way:

V [x] - 100



I'm going to post a new related and very similar question - How to define a vector R where some names are in variables.

0


source


We can do this using setnames

setNames(c(V, 100), c(names(V), x))

      

Adding an example,



V <- c(a = 1, b=2)
V
#a b 
#1 2 
x <- "c"
setNames(c(V, 100), c(names(V), x))
# a   b   c 
# 1   2 100 

      

Or, as @thelatemail suggested, we could only work with an extra element

c(V, setNames(100,x))

      

+4


source







All Articles