Ernie
Ernie

Reputation: 1153

Replace values in named vector with values from another named vector

I have two vectors, say :

x <- c(2, 3, 5, 7, 9, 11)
names(x) <- c("a", "b", "c", "d", "e", "f")
y <- c(33,44,55)
names(y) <- c("b", "d", "f")

so that x is

a  b  c  d  e  f 
2  3  5  7  9 11 

and y is

 b  d  f 
33 44 55 

I want to replace the values in x with values in y that have the same name so that the result would be for the new x:

a  b  c  d  e  f 
2 33  5 44  9 55 

I'm sure this has been answered somewhere but I can't find it.

Upvotes: 12

Views: 4773

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

You can use the names of y as a subset on x, then replace with y.

x[names(y)] <- y
x
# a  b  c  d  e  f 
# 2 33  5 44  9 55 

Another option is replace(), which basically does the same as above but returns the result and does not change x.

replace(x, names(y), y)
# a  b  c  d  e  f 
# 2 33  5 44  9 55 

Upvotes: 12

Related Questions