absolute.sum<-function(n) ## a function that adds from -n to n { a<-0 for(i in -n:n) { if(i>=0) a<-a+i ## if i is positive, add i to a else a<-a+(-i) ## if i negative, add the absolute value -i to a } return(a) } > absolute.sum(100)
Tip: looping is very expensive in R. Always avoid looping if possible
absolute.sum1<-function(n) ## this is another version of faster implementation { return(sum(abs(-n:n))) } absolute.sum(1000000) ## this will take a while absolute.sum1(1000000) ## this will take less than a second