Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting a named vector from another named vector

Tags:

r

vector

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.

like image 579
Bogaso Avatar asked Jan 30 '26 22:01

Bogaso


2 Answers

`[<-`(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
like image 94
M-- Avatar answered Feb 02 '26 11:02

M--


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
like image 39
Andre Wildberg Avatar answered Feb 02 '26 12:02

Andre Wildberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!