-2

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

WHN
  • 27
  • 5
  • 1
    Hi! Please provide us with a small, reproducible code snippet that we can copy and paste to better understand the issue and test possible solutions. You can share datasets with `dput(YOUR_DATASET)` or smaller samples with `dput(head(YOUR_DATASET))`. (See [this answer](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#5963610) for detailed instructions.) – ktiu Jun 05 '21 at 16:33

1 Answers1

1

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.

Ben
  • 28,684
  • 5
  • 23
  • 45