NMST539, LS 2015/16Cvičenie 2 (týždeň 3)(Mnohorozmeré normálne rozdelenie)(R package mvtnorm)To begin, we need to make sure that the corresponding library is loaded in the R working environment (use commad
Using the loaded library one can easily generate random values from some multivariate normal distribution. CommentOnce we are about to use some random generator in R (or any other software) it is good to predefine the initial values for the generator (in R there is a command called set.seed() which can be used for this). By doing so one makes sure that the results are all reconstructable. Let us start with some very simple (two-dimensional only) example. We will generate a sample from the distribution where \(\Sigma\) is the variance-covariance matrix. Remember, that in case of a uniform random generator (command
And we can plot the generated random sample into a scatterplot using the following command:
Using now sample mean estimates and sample variance-covariance matrix we can easily draw some ‘depth’ contours in the figure. The other option is to use theoretical values as we know them as well however, for the following we will rather stick with the sample only and we use sample mean vector and sample variance-covariance matrix.
The two dimensional normal density function is given by where \(\boldsymbol{x} = (x_1, x_2)^{\top}\) and \(\boldsymbol{\mu} = (\mu_{1}, \mu_2)^{\top}\). Thus, we also need the inverse matrix for the sample variance-covariance matrix \(\hat{\Sigma}\) to be able to draw the corresponding contours. The fuction called
And now we can draw contours
Try by yourselves
Two dimensional normal from one dimensionalFinally, we can generate a ‘two dimensional normal’ from one dimensional by using some reasonable transformation but one can not directly control for the covariance of the two covariates being generated.
Domáca úloha(Deadline: piaty týždeň / 21.03.2016)Na webovej stránke Doc. Hlávku http://www1.karlin.mff.cuni.cz/~hlavka/teac.html je k dispozícii niekoľko dátových súborov, ktoré do Rka stačí načítať pomocou príkazu
|
Comment
There is also a predefined function in R called
ellipse()
which can be found in the R packagemixtools
. Install the library usinginstall.packages(mixtools)
and try to following piece of code:How is the the elipse actually calculated?
Another option for simulating multivariate normal sample is available in the library
MASS
by using commandmvrnorm()
: