Using for loop for summation in R

10,521

Solution 1

This is likely because you aren't storing your result of intermediate a steps so you only get the result of the final calculation.

You can get the total sum (using a loop) with:

# Initialize variable with the sum 
my.sum = 0
for(i in 1:8){
    current = (xvalues[i]*yvalues[i])-284400*(i)
    # Update variable storing sum
    my.sum = my.sum + current
}
> my.sum

Alternatively, you can vectorize the calculation using:

i = 1:8
sum((xvalues[i]*yvalues[i])-284400*(i))

Solution 2

Just use sum(df$X * df$Y - 284400*(1:nrow(df)))

Or you can use dplyr for that:

library(dplyr)
df %>%
  mutate(value = X * Y - 284400 * row_number()) %>%
  summarise(sumvalue = sum(value))
Share:
10,521

Related videos on Youtube

yerman
Author by

yerman

Updated on June 04, 2022

Comments

  • yerman
    yerman almost 2 years

    This is probably extremely obvious but I've been trying without success to fix it for about an hour (I'm kinda a beginner):

    The function is a sum from 1:8 of the expression: xi*yi - 284400(i) where xi and yi are from a data frame with two columns X and Y both of length 8. I'm just trying to find the numerical value without having to calculate it myself.

    I tried the following code, but when using the for loop it seems to keep assigning i an integer value of 8. Am I using the for loop incorrectly?

    Note: I made a vector of the x column called 'xvalues' and similarly the y column was called 'yvalues'

    for(i in 1:8){
        sum((xvalues[i]*yvalues[i])-284400*(i))
        }
    

    After running this I keep getting a null output and when I call i, it just gives:

    [1] 8
    

    Thanks in advance!

    • jogo
      jogo about 5 years
      sum(xvalues * yvalues - 284400*(1:8)) ... without a loop.
    • Julian_Hn
      Julian_Hn about 5 years
      Hello. Do you want to get the sum of this product for each value-pair xvalues/yvalues or the total sum of all operations?