Kwaku Orgen
Kwaku Orgen

Reputation: 11

simulation a while loop

there might be some threads on while loops but I am struggling with them. It would be great if someone could help an R beginner out.

So I am trying to do 10000 simulations from a an out of sample regression forecast using the forecast parameters: mean, sd. Thankfully, my data is normal.

This is what I have

N<-10000
i<-1:N
k<-vector(,N)
while(i<N+1){k(,i)=vector(,rnorm(N,mean=.004546,sd=.00464163))}

...and I get this error

Error in vector(, rnorm(5000, mean = 0.004546, sd = 0.00464163)) : 
invalid 'length' argument
In addition: Warning message:
In while (i < N + 1) { : the condition has length > 1 and only the first element will be used

I can't seem to get my head around it.

Upvotes: 1

Views: 581

Answers (3)

Viktor Ek
Viktor Ek

Reputation: 353

To solve your problem, use @Esben Friis' answer. You are taking a hard approach to an easy problem.

To adress the questions you had about the error messages you got however:

Error in vector(, rnorm(5000, mean = 0.004546, sd = 0.00464163)) : 
invalid 'length' argument

This is the wrong way to go as vector() will produce a vector of a set length instead of a set of values. You are thinking about the as.vector() function:

as.vector(rnorm(5000, mean = 0.004546, sd = 0.00464163))

This is however not needed as this will only create a new vector of your values, which are already in a vector structure of the type double. Using this function will therefore not change anything.

It is best to simply use:

rnorm(5000, mean=0.004546, sd=0.00464163)

Further:

In addition: Warning message:
In while(i<N+1){: the condition has length>1 and only the first element will be used

This warning stems from i being a vector 1:N with a length larger than 1. The warning states that only the first index in i will be recycled (used in all instances of the loop) which is the same as doing i[1] .

while(i<N+1){ }
#is the same as
while(i[1]<N+1){ }

Instead you want to loop a new value to N. Furthermore you can use the <= (less or equal to) operator instead of doing <N+1 .

while(newVal<=N){ }

This method will bring up new problems which could be solved by using a for() loop instead, but that is however out of the scope of the question and really not the right approach to your problem, as stated in the beginning. Hope you learned something and good luck!

Upvotes: 0

Math
Math

Reputation: 1294

try this

N<-10
i<-1
k<-matrix(0,1,N)
while(i<N+1){k[i]=rnorm(1,mean=.004546,sd=.00464163)
i=i+1
}
print(k)

Upvotes: 0

Esben Friis
Esben Friis

Reputation: 61

No reason to create a loop here. If you want to put 10000 samples, normal distributed around mean = 0.004546 and sd = 0.00464163 into vector k, just do:

k <- rnorm(10000,mean = 0.004546, sd = 0.00464163)

Upvotes: 2

Related Questions