yerman
yerman

Reputation: 287

Using for loop for summation in R

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!

Upvotes: 2

Views: 21464

Answers (2)

NM_
NM_

Reputation: 1999

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))

Upvotes: 3

Sonny
Sonny

Reputation: 3183

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))

Upvotes: 1

Related Questions