0

I want to sum all elements of vectors together. However, I am trying to exclude the last element of each vector. For example,

vector1 <- c(10,20,3000)
vector2 <- c(20,40,5000)

sum(vector1, vector2)
[1] 8090

But I would like to exclude the 3000 in vector1 and the 5000 in vector2 to output [1] 90. Also, this is just a reproducible example, my real vectors don't have the same consistent number of elements. Could this be done?

Cettt
  • 11,460
  • 7
  • 35
  • 58
Rebecca
  • 45
  • 5
  • Relevant [remove the last element of a vector](https://stackoverflow.com/questions/12114439/remove-the-last-element-of-a-vector) – markus Nov 09 '19 at 13:10

3 Answers3

3

You can use head to remove the last element and sum

sum(head(vector1, -1), head(vector2, -1))

Or do

sum(vector1[-length(vector1)], vector2[-length(vector2)])
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

You can deselect the last item of your vector before performing the sum:

vector1 <- c(10,20,3000)
vector2 <- c(20,40,5000)

sum(vector1[-length(vector1)], vector2[-length(vector2)])
Hart Radev
  • 361
  • 1
  • 10
1

You can manually exclude the last component. One possibility is this:

sum(rev(vector1)[-1], rev(vector2)[-1])

rev reverses a vector, [-1] selects all but the first element (of the reversed vector).

Cettt
  • 11,460
  • 7
  • 35
  • 58