I have 2 vectors as below
Vec1 = c(1,2,3,4)
names(Vec1) = c('Val1', 'Val2', 'Val3', 'Val4')
Vec2 = c(10, 11)
names(Vec2) = c('Val2', 'Val4')
Is there any easy way to subtract Vec2 from Vec1 based on same names in the vector element? The names which are not available in Vec2 can be assumed to have zero value.
`[<-`(Vec1, names(Vec2), Vec1[names(Vec2)] - Vec2)
## OR using replace() without creating a helper variable
Vec1 |> replace(names(Vec2), Vec1[names(Vec2)] - Vec2)
Result:
#> Val1 Val2 Val3 Val4
#> 1 -8 3 -7
If Vec1 always has the full length (and Vec2 may or may not have missing entries) an approach using replace
Vecs <- Vec2[names(Vec1)]
Vec1 - replace(Vecs, is.na(Vecs), 0)
Val1 Val2 Val3 Val4
1 -8 3 -7
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