Adding vector elements with a condition in R

Suppose I have an element vector that I want to add:

a <- c(1,2,-7,5)

Here are some additional test cases:

a <- c(1,2,-3,5)
a <- c(1,2,-7,-3,5)

I know what I can use sum(a)to get the result, but what if I had a condition to keep track of:

current_sum = 0
for(i in 1:length(a)){    
 last_sum = current_sum
 current_sum = current_sum + a[i]
 if(current_sum < 0)
 {
  current_sum = last_sum
  current_sum = current_sum + (a[i]*-1)
 }
}

Here, every time the amount is negative, we return to the previous amount and add the opposite to the number that made the amount negative. Conclusion 15 as a result of the first example

Obviously, the element vector is unknown before the hand and performance problems. Is there a completely vectorized method in general or a more efficient way to do this at all (avoiding loops)?

+4
3

, R/C , , R, C . :

require(inline)
.internalSumPositive<-cfunction(sig=c(v="SEXP"),body="
   double sum=0.0;
   int i,n = length(v);
   double *values = REAL(v);
   SEXP ret = PROTECT(allocVector(REALSXP,1));
   for (i=0;i<n;i++) {
      sum += values[i];
      if (sum<0) sum = sum - 2*values[i];
   }
   REAL(ret)[0] = sum;
   UNPROTECT(1);
   return ret;")

sumPositive<-function(v) {
   if (!is.numeric(v)) stop("Argument must be numeric")
   if (length(v)==0) return(numeric(0))
   .internalSumPositive(as.numeric(v))
}

:

sumPositive(c(1,2,-7,5))
#[1] 15
sumPositive(c(1,2,-3,5))
#[1] 5
sumPositive(c(1,2,-7,-3,5))
#[1] 12

, R- ( ).

+5

f1 <- function(x) repeat{pos<-min(which(cumsum(x)<0))
                    x[pos]<-abs(x[pos])
                    if(all(cumsum(x)>=0)){return(sum(x));break}}
a <- c(1,2,-7,-3,5)
f1(a)
#[1] 12
+4

Reduce, :

a <- c(1,2,-7,5)
Reduce(function(x, y){x + ifelse(x + y < 0, -y, y)}, a)
## [1] 15

a <- c(1,2,-3,5)
Reduce(function(x, y){x + ifelse(x + y < 0, -y, y)}, a)
## [1] 5

a <- c(1,2,-7,-3,5)
Reduce(function(x, y){x + ifelse(x + y < 0, -y, y)}, a)
## [1] 12
+4

All Articles