简体   繁体   中英

Adding up a vector without the sum function

I am trying to learn programming with R.

Can someone show me how to sum this vector without using the function sum ? This is just an exercise that I am trying to do.

From the package MASS , the data abbey :

[1]   5.2   6.5   6.9   7.0   7.0   7.0   7.4   8.0   8.0   8.0   8.0   8.5   9.0     9.0  10.0  11.0  11.0  12.0
[19]  12.0  13.7  14.0  14.0  14.0  16.0  17.0  17.0  18.0  24.0  28.0  34.0 125.0

I would like to sum only the values above the value 10.

So the result should be as it would be with the function sum :

sum(abbey[abbey>10])

380.7

I was trying to do it with the for loop and if else function, and have managed to do this thus far:

y= for (i in seq(abey)) {

  if(i>10) { sum(i)} 

}

But it returns

NULL

Thank you!

You can use Reduce with + .

Reduce("+", abbey[abbey > 10])
# [1] 380.7

Alternatively, you could use the cumulative sum. This is quite a bit faster than Reduce

rev(cumsum(abbey[abbey > 10]))[1]
# [1] 380.7

Another way would be to use Recall in a custom function. Recall is used as a placeholder for the name of the function in which it is called. So in this function mySum , it sums the values recursively.

mySum <- function(x) {
    if(length(x) == 2) { 
        x[1] + x[-1] 
    } 
    else {
        x[1] + Recall(x[-1])
    }
}
mySum(abbey[abbey > 10])
# [1] 380.7

Simple for loop:

    Sum<-0
    for (i in abbey) if (i>10) Sum<-Sum+i
    Sum
    #[1] 380.7

However, this way can be very slow compared to the sum function.

You could do an inner product with a vector filled with ones.

abbey2 <- abbey[abbey > 10]
as.numeric(t(matrix(abbey2)) %*% rep(1, times = length(abbey2)))
# [1] 380.7

I see you are into for loops (judging by all of your recent questions), for loops are "expensive" in R. Instead, you might want to consider checking the Rcpp package which allows you writing efficient for loops in C++ and compile them to R

For example (taken from Haley's Advaned R . (Sorry @Dirk, was too lazy to write it on my own :)))

library(Rcpp)
cppFunction('double sumC(NumericVector x) {
  int n = x.size();
  double total = 0;
  for(int i = 0; i < n; ++i) {
    total += x[i];
  }
  return total;
}')

library(MASS)
sumC(abbey[abbey > 10])
## [1] 380.7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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