Victor Nielsen
Victor Nielsen

Reputation: 493

I can't find the mistake in my for loop code in r

I have this code:

test_x <- 2000

#functions used:

`%+<-%` = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2))

CreateData <- function()
{
numeric(test_x)
}

#variables

test_sum <- 0
test_q <- 0
test_q <- CreateData()
test_Q <- 0
test_Q <- CreateData()
test_step <- 0.01

#two for loops

for (i in test_x) {
  test_q[i] <- 40
}
for (i in (test_x - 1):0) {
  test_sum %+<-% (test_q[i]*test_step)
  test_Q[i] <- test_sum
}

I'm expecting that the first for loop would fill test_q with 40 in each of the 2000 locations, but instead each spot is zero. The second loop thus also stays zero.

No errors. What did I do wrong?

Upvotes: 0

Views: 19

Answers (1)

Basti
Basti

Reputation: 1763

In the first loop i is only taking the value 2000, then you should modify the first loop as follows :

for (i in 1:test_x) {
  test_q[i] <- 40
}

Upvotes: 1

Related Questions