Search code examples
rentropy

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

Thanks


Solution

  • We can use Reduce with -

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

    Or use sum

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