Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace values in named vector with values from another named vector in R

Tags:

r

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.

like image 696
Ernie Avatar asked Oct 21 '15 22:10

Ernie


1 Answers

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 
like image 192
Rich Scriven Avatar answered Sep 28 '22 03:09

Rich Scriven