R: sum of negative values ​​in a vector only if they are preceded by positive values

I have a vector that looks like this:

mass<-c(-2, -6, -79, 31, -28, 198, 132, 0, 262, -187, -475, 701, 926) 

I need to summarize the following subset of values ​​from this vector:

  • all positive values;
  • negative values ​​if they precede the vector with a positive value.

So, in the above example of the vector, I would like to exclude -2, -6 and -79 from the sum (they do not correspond to positive values), but include -28, -187 and -475 (since they precede the vector with positive values).

I can judge. positive values ​​with

 sum(mass[mass>0]) 

But I'm not sure how to include only those negative values ​​that match my criteria.

(I have a large number of vectors for which I need to perform a similar operation, and they do not all have the same sequence of negative / positive values, so I also can’t just solve this problem by multiplying the vector to exclude the first three values, so how the number of excluded values ​​will differ depending on the vector).

Thanks so much for any help!

+4
source share
3 answers
 ones.you.want <- intersect(which(mass < 0), which(mass > 0)[1]:length(mass)) sum(mass[ones.you.want]) 

Note. This can cause a crash if there are no positive values ​​in the vector.

+4
source

Following the Rguy entry, here is an alternative that also works if all vector elements are negative:

 getElements <- function(X) { id <- which(X > 0 | # +'s c(FALSE, diff(sign(X))==-2) # - after +. (1st element always FALSE) ) return(X[id]) } getElements(mass) # [1] 31 -28 198 132 262 -187 701 926 getElements(-1:-10) # integer(0) 
+1
source
 sum( mass[-1][ mass[-1] < 0 & mass[-length(mass)] > 0 ] ) 
0
source

Source: https://habr.com/ru/post/1379016/


All Articles