Can you explain the structure/idea of loop in R-Code? I don't know where to start with this homework problem. I was able to create the exponential distribution I needed with
> rexp(n=200, rate=0.5)
but now I need to create 2,000 samples of this rexp and calculate the mean of each sample. Then I need to calculate the mean and variance of the 2,000 sample means. I know how to find the mean and variance of a simple distribution (ex: mean(rexp) and var(rexp)), so my main issue is understanding this concept of a loop and putting it into action.
So I started with entering:
> rexp(n=200,rate=0.5)
Then I named this exponential distribution:
> exdi = rexp(n=200,rate=0.5)
Based off of an example dealing with sums, I entered
>y.exdi=vector(length=2000)
>for(i in 1:2000){y.exdi[ i ]=mean(exdi)}
The R Workspace gave no response to this, so I named the function and tried this:
>Twothou = for(i in 1:2000){y.exdi[ i ]=mean(exdi)}
>mean(Twothou)
But then I got this error message:
[1] NA
Warning message:
In mean.default(Twothou) : argument is not numeric or logical: returning NA
What should I do differently?
A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number.
Let's go over the syntax of the for loop: It starts with the for keyword, followed by a value name that we assign to the item of the sequence ( country in this case). Then, the in keyword is followed by the name of the sequence that we want to iterate. The initializer section ends with “ : ”.
You've just created a really nice vector of 2000 elements of the same value - in the means of the mean of your sample brewed for exponential distribution only once. See by checking y.exdi in your console.
If you want to use a loop for this solution, you should create new and new samples in each iteration. You may do that easily with e.g. sapply (wrapper around the for loop) applied to 1:2000:
sapply(1:2000, function(x) mean(rexp(n = 200, rate = 0.5)))
Or rather directly calling e.g. replicate (that was intended to be used for such cases):
replicate(2000, mean(rexp(n = 200, rate = 0.5)))
I think you should put the random number generator rexp inside your for loop:
y.exdi=vector(length=2000)
for(i in 1:2000){
y.exdi[ i ]=mean(rexp(n=200,rate=0.5))
}
Otherwise, for each i you just calculate the mean of a fixed vector defined outside the loop, instead of new ones generated each time the index i increases. Having that codes above, you can calculate the mean using mean(y.exdi), which gives you the average of the 2000 "averages".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With