TU Wien:Statistik und Wahrscheinlichkeitstheorie UE (Levajkovic)/Übungen 2023W/HW12.3

Aus VoWi
Zur Navigation springen Zur Suche springen
Correlation 3

Let and . Plot 150 realizations of ( plotted against , ) for each of the values of their correlation . To each plot add lines with and obtained according to Problem 2. Compute the empirical correlation of the

realizations and add it to your plots.

Dieses Beispiel ist als solved markiert. Ist dies falsch oder ungenau? Aktualisiere den Lösungsstatus (Details: Vorlage:Beispiel)


Lösungsvorschlag von Lessi[Bearbeiten | Quelltext bearbeiten]

--Lessi 2024-02-07T13:04:11Z

# Let X ∼ N(3, 1) and Y ∼ N(2, 4). Plot 150 realizations of (X, Y ) (y_i plotted against x_i,
# i = 1, . . . , 150) for each of the values of their correlation Corr(X, Y ) ∈ {0, 0.8, −0.5, −1}. 

# To each plot add lines {(x, y) ∈ R^2 | y = β0 + β1x }
# with β0 and β1 obtained according to Problem 2. 

# Compute the empirical correlation r of the realizations and add it to your plots.

rm(list = ls())
par(mfrow=c(2,2))

n <- 150

mu_x <- 3
mu_y <- 2
sigma_x <- 1
sigma_y <- 2

x <- rnorm(n, mu_x, sigma_x)
y <- rnorm(n, mu_y, sigma_y)

plot_stuff <- function(rho) {
  beta_1 <- rho * sigma_y / sigma_x
  beta_0 <- mu_y - beta_1 * mu_x
  
  plot(x, y, main=paste(c("Correlation with rho=", rho), collapse = " "))
  
  abline(beta_0, beta_1, col='red')
  
  
  m_x <- mean(x)
  m_y <- mean(y)
  s_x <- sqrt(var(x))
  s_y <- sqrt(var(y))
  
  r <- cor(x, y)
  
  b_1 <- r * s_y / s_x
  b_0 <- m_y - b_1 * m_x
  
  abline(b_0, b_1, col='blue')
  mtext(paste(c("r=", r)), 3)
}

plot_stuff(0)
plot_stuff(0.8)
plot_stuff(-0.5)
plot_stuff(-1)