Amit Amit - 7 months ago 39
R Question

How to subtract elements of vector in r

I have a vector in R

myVect <- c(1,2,3,4)

Output i am looking for is

1-2-3-4 =-8

Is there a function that i can use for this



We can use Reduce with -

Reduce(`-`, myVect)
#[1] -8

Or use sum

sum(c(myVect[1], -1*myVect[-1]))
#[1] -8