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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With