#Help to exercise 1 in the R-exercises

 

# You may copy the commands from the web-browser into the command-window of R (or into a R-script).

# ?A line that starts with # is a comment, and R will disregard such lines.

 

 

# QUESTION a)

 

# Generate n=10 standard normally distributed random variables and compute the mean and the empirical variance

# (alternatively you may use equality sign = instead of assignment arrow <- in the commands):

n<-10

x<-rnorm(n)

mean(x)

var(x)

 

# Repeat the computations for n=100, 1000, 10000, and 1000000 and note how the mean and the empirical variance change with the value of n.

 

 

# QUESTION b)

 

# Generate n=10 uniformly distributed random variables over [0,1] and compute the mean and the empirical variance

# (the density of the uniform distribution over [0,1] is f(x)=1 for 0<x<1 and f(x)=0 otherwise):

n<-10

x<-runif(n)

mean(x)

var(x)

 

# Repeat the computations for n=100, 1000, 10000, and 1000000 and note how the mean and the empirical variance change with the value of n.

# Can you guess the true (theoretical) values of the mean and variance?

 

# Do similar computations for the exponential distribution with parameter lambda=1.

# (The density of this distribution is f(x)=exp(-x) for x>0 and f(x)=0 otherwise.)

 

 

# QUESTION c)

 

# Generate n=10 standard normally distributed random variables and compute the empirical median and quartiles

# (alternatively you may use the command quantile(x) to find the quartiles):

n<-10

x<-rnorm(n)

summary(x)

 

# Repeat the computations for n=100, 1000, 10000, and 1000000 and note how the empirical median and quartiles change with the value of n.

# What are the limits of the empirical median and quartiles as n increases?

# You may find the true (theoretical) median and quartiles by the command qnorm(c(0.25,0.5,0.75))

 

# Repeat the computations for the uniform distribution and the exponential distribution.

 

 

# QUESTION d)

 

# Generate n=10 uniformly distributed random variables and compute their mean.

# Repeat this 1000 times, so that you get 1000 values of the mean, and make a histogram of these:

n<-10

x<-runif(n)

meanx<-mean(x)

for (i in 1:1000)

{

? ??x<-runif(n)

? ??meanx<-c(meanx,mean(x))

}

hist(meanx)

 

# How does the histogram look like compared to a normal distribution?

 

# (We use a loop to generate the 1000 values of the mean. There are more efficient ways to do this in R, but we will not discuss such methods here.)

 

#Repeat the computations for the exponential distribution with n=10 and n=100. What do you see?