Amit Amit - 1 year ago 109
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


Answer Source

We can use Reduce with -

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

Or use sum

sum(c(myVect[1], -1*myVect[-1]))
#[1] -8
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download