Search code examples
rfor-loopsum

For loop for summation in R


Suppose I have the following summation. [summation image]. How do I write a for loop such that I can store the values into a vector for j = 1 all the way through j = m.

I tried the following

theta1 <- 1
theta2 <- 2

z = c()
for(i in 1:j){
 z[i] <- sum(exp[(theta1 * j + theta2 * j)
}

However, I get a vector of length j with only the same outputs


Solution

  • Looking at the equation, this might be what you are looking for.

    First, you began with an empty vector z:

    z = c()
    

    Using your equation terms, let's call the index, j. You may then want a for loop from 1 to m (make sure to define m). Each element could then be computed as follows:

    for (j in 1:m) {
      z[j] <- exp((theta1 * j) + (theta2 * (j ^ 2)))
    }
    

    The final sum of the vector elements would be:

    sum(z)
    

    Since exp is vectorized, you could consider the following alternative, instead of using a for loop:

    j <- 1:m
    sum(exp((theta1 * j) + (theta2 * (j ^ 2))))
    

    This should provide the same answer.