S.Galleg S.Galleg - 2 months ago 23
R Question

Using for loop in r to get a cumulative sum

I need to solve for the sum of (10^2 + 10^3) 99 cumulative times, so the sum of (1100+1100+1100...(99 times))=Total. I know most people don't like loops but I need to solve for this using a for loop. Here is what I have so far...

prob1 <- function(n){
total <- 1100
for(i in 2:99)
total[i] <- sum(i^2 + i^3)
return(total)
}


This is what I get

[1] 1100 12 36 80 150 252 392 576 810 1100 1452 1872 2366 2940 3600
[16] 4352 5202 6156 7220 8400 9702 11132 12696 14400 16250 18252 20412 22736 25230 27900
[31] 30752 33792 37026 40460 44100 47952 52022 56316 60840 65600 70602 75852 81356 87120 93150
[46] 99452 106032 112896 120050 127500 135252 143312 151686 160380 169400 178752 188442 198476 208860 219600
[61] 230702 242172 254016 266240 278850 291852 305252 319056 333270 347900 362952 378432 394346 410700 427500
[76] 444752 462462 480636 499280 518400 538002 558092 578676 599760 621350 643452 666072 689216 712890 737100
[91] 761852 787152 813006 839420 866400 893952 922082 950796 980100


How can I get it to add correctly and return just the total?
The total should be 108,900 (I believe)

Answer

I looked at your loop issue a little differently since you just wanted the total. Your code was adding elements to a vector with the total[i]. You instead want to just have i be an iterator for adding a number to another number. I initialized that to 0 with the first line.

total=0
for (i in 1:99) {
total<-total+(10^2 + 10^3)
i=i+1
}
total

[1] 108900

1100*99

[1] 108900