2

Is it possible to avoid using do and while loops to calculate the sum of the elements of a vector until the appearance of the last positive element or the last negative element.

Ali H
  • 21
  • 1
  • 1
  • 5

1 Answers1

6

Try the following:

x <- 5:-5
# sum until last positive:
sum(x[1:max(which(x > 0))])

x <- -5:5
# sum until last negative:
sum(x[1:max(which(x < 0))])

Explanation:

Which(x > 0) gives a vector of index numbers at which x is greater than 0. Taking the max of this gives the last such index. Then all that remains is summing up x from 1 up to this element. I hope this helps.

Edward
  • 5,367
  • 1
  • 20
  • 17
  • I think this is what I needed. What did u wanted me to do Tyler. – Ali H Aug 07 '12 at 13:11
  • Edward, I am happy to explain, its a vector which is randomly generated. I need to find the sum of all the elements until the appearnce of the first postive number. Thanks for your help – Ali H Aug 07 '12 at 13:12
  • Edward, Shouldnt there be min instead of max for the last negative one. And I want the sum of all the elements until the appearance of the last neagative element. – Ali H Aug 07 '12 at 13:17
  • For the first appearance, use `min`. For the last appearance, use `max`. – Edward Aug 07 '12 at 13:17
  • 1
    Ali here's a [LINK](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on how to make a reproducible example. it'll get you better results and faster. – Tyler Rinker Aug 07 '12 at 13:18
  • 2
    There's also `which.max` which handles this common use case. – Ari B. Friedman Aug 07 '12 at 13:45
  • 1
    @Edward this fails when x has length 0, or no elements satisfy the condition. – Martin Morgan Aug 07 '12 at 14:01
  • That's a good point Martin, definitely should be taken into consideration. You could do something like: `end.range <- which(x > 0)` and then do checking as follows: `if (length(end.range) == 0){sum(x)} else {sum(x[1:max(end.range)])}` (it would obviously depend on what you want the behavior to be in the case of this exception). Thanks for pointing it out. – Edward Aug 07 '12 at 14:09