Generate 100 random vectors \(X_1,\ldots, X_{n}\) (\(n=100\)) from the bivariate normal distribution \(\mathcal{N}(\mu,\Sigma)\), where \(\mu=(1,2)^\intercal\) and \[ \Sigma = \begin{bmatrix} 1 & 0.5 \\ 0.5 & 2 \end{bmatrix}. \] Compute the sample mean vector and the sample covariance matrix: \[ \hat \mu = \frac{1}{n} \sum_{i=1}^n X_i ~~\mbox{ and }~~ \hat \Sigma = \frac{1}{n} \sum_{i=1}^n (X_i- \hat \mu) (X_i - \hat \mu)^\intercal . \]
This can be done using the function in the package:
library(MASS)
Sigma <- matrix(c(1,0.5,0.5,2),2,2)
mu <- c(1, 2)
X <- mvrnorm(n = 100, mu, Sigma)
# n by 2 data matrix X: each row represents a sample
head(X)
## [,1] [,2]
## [1,] 1.5095904 1.19634149
## [2,] 1.5232664 3.29298655
## [3,] 0.8176725 0.47466701
## [4,] 1.4941909 1.38292277
## [5,] -0.3138479 -0.02347093
## [6,] 2.0448483 3.04146990
# Sample mean vector
smean <- colMeans(X)
# Sample covariance matrix
n <- dim(X)[1]
X0 <- X - matrix(smean, nr = n, ncol = 2 , byrow = TRUE)
# Centered data matrix X0: each row represents a sample vector minus the sample mean
scov <- t(X0) %*% X0 /n
Write an function that outputs the first \(n\) terms in the Fibonacci sequence, where \(n\) is the only input value of the function.
# construct the function
fibonacci <- function(n)
{
x = numeric(n)
x[1:2] = c(1,1)
for(i in 3:n) x[i] = x[i-1] + x[i-2]
return(x)
}
# test the function
fibonacci(10)
## [1] 1 1 2 3 5 8 13 21 34 55
Instead, using echo = FALSE in the code chunk prevents printing of the R code that generated the function