简体   繁体   中英

Add every element in a vector in R without using 'SUM' function

I am trying to get the total of every element in a vector without using any inbuilt functions:

x <- 1:6
arraysum <- function(x){
  for (i in 1:length(x)) {
    y <- 0
    y <- i+1
  }
  print(y)
}

But I am getting output 7 instead of 21. Could someone please let me know where I am going wrong?

Just use Reduce :

Reduce(`+`, x)
# [1] 21

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