Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

elementname

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
like image 956
tedtoal Avatar asked May 23 '17 22:05

tedtoal


People also ask

How do you add a name to a vector in R?

We can add names to vectors using two approaches. The first uses names() to assign names to each element of the vector. The second approach is to assign names when creating the vector. We can also add comments to vectors to act as a note to the user.

Which function is used to give a name to the elements of a vector?

We use names() function for giving the name of vector element.

How do you name vectors?

We can assign names to vector members. For example, the following variable v is a character string vector with two members. We now name the first member as First, and the second as Last. Then we can retrieve the first member by its name.


Video Answer


2 Answers

We can do this by 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 on the additional element

c(V, setNames(100,x))
like image 94
Ronak Shah Avatar answered Nov 14 '22 21:11

Ronak Shah


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.

like image 38
tedtoal Avatar answered Nov 14 '22 21:11

tedtoal