简体   繁体   English

R:仅当向量中的负值前面为正值时才对它们求和

[英]R: sum 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 sum the following subset of values from this vector: 我需要从这个向量求和以下值的子集:

  • all positive values; 所有正面价值;
  • negative values if they are preceded in the vector by positive value. 如果它们在向量中以正值开头, 则为负值。

So in the example vector above, I would like to exclude -2, -6, and -79 from the sum (they do not follow positive values), but include -28, -187, and -475 (since they are preceded in the vector by positive values). 所以在上面的示例向量中,我想从总和中排除-2,-6和-79(它们不遵循正值),但包括-28,-187和-475(因为它们在前面是正值的矢量)。

I can sum. 我可以总结。 positive values with 积极的价值观

sum(mass[mass>0])

But I'm not sure how to include only those negative values that meet my criteria. 但我不确定如何只包括那些符合我标准的负值。

(I have a large number of vectors I need to perform a similar operation for, and they do not all have the same sequence of negative/positive values, so I also can't just deal with this problem by subsetting the vector to exclude the first three values, since the number of values to be excluded will differ depending on the vector). (我有大量的向量需要执行类似的操作,并且它们并不都具有相同的负/正值序列,所以我也不能通过对向量进行子集化来排除这个问题来解决这个问题前三个值,因为要排除的值的数量将根据向量而不同)。

Thank you very much for any help! 非常感谢您的帮助!

ones.you.want <- intersect(which(mass < 0), which(mass > 0)[1]:length(mass))
sum(mass[ones.you.want])

Note: This could fail if there are no positive values in the vector. 注意:如果向量中没有正值,则可能会失败。

Following up on Rguy's note, here's an alternative that also works if the vector elements are all negative: 按照Rguy的说明,这里有一个替代方案,如果向量元素都是负数,也可以使用:

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)
sum( mass[-1][ mass[-1] < 0 & mass[-length(mass)] > 0 ] )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM