Search code examples
relementname

How add named element to R vector with name from a variable


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

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

but I'm looking for an easy single-line solution, if there is one. I tried:

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

and

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

but those don't work.

Okay, discovered best way:

V[x] = 100

Solution

  • 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 an R vector where some names are in variables.