-1

I am trying to plot the conditional distributions from the bivariate normal using the joint and marginal distributions.

The conditional distribution of X given Y is X|Y=y~N(rho * y,1-rho^2) and Y given X is Y|X=x~N(rho*x,1-rho^2)

Here is my approach to implement this in R using simulation (taking the particular value of rho=1/2 in both the joint and marginal dist. for more info see here :

plot.new()

num<-exp(-2*((x^2)-(x*y)+(y^2))/3)
den<-(exp((-x^2)/2)*sqrt(3))/sqrt(2*pi)

quot<-num/den

fun <- function(x, y){quot} 

xs <- seq(-10, 10, by=1)
ys <- seq(-10, 10, by=1)

res <- mapply(fun, list(xs), list(ys))

cols <- c("black", "cornflowerblue", "orange")
matplot(xs, res, col=cols, type="l", lty=1, lwd=2, xlab="x", ylab="result")
legend("bottomright", legend=ys, title="value of y", lwd=2, col=cols)

When I run the code I get the message error

Error in matplot(xs, res, col = cols, type = "l", lty = 1, lwd = 2, xlab = "x", : 'x' and 'y' must have same number of rows

why does it says that x and y must have same number of rows? In which part of the code can I fix this?

I don't get it, please help me.

user9802913
  • 245
  • 4
  • 20
  • I based my question in the answer given here https://stackoverflow.com/questions/47879000/how-to-graph-function-with-two-variables-in-r – user9802913 Jun 16 '19 at 15:23
  • Why is the code for calculating `quot` outside the function body? – Rohit Jun 16 '19 at 16:06
  • @Rohit Oh should be inside? I though the order didn't matter. I did modify it but still I get the message error: `Error in matplot(xs, res, col = cols, type = "l", lty = 1, lwd = 2, xlab = "x", : 'x' and 'y' must have same number of rows` – user9802913 Jun 16 '19 at 17:08

1 Answers1

0

I've solved the problem :)

Consider the following

 fun <- function(x, y){(exp(-2*((x^2)-(x*y)+ 
   (y^2))/3))/((exp((-x^2)/2)*sqrt(3))/sqrt(2*pi))}

    xs <- seq(-5, 5, by=.01)
    ys <- seq(-5, 5, by=.01)

    res <- mapply(fun, list(xs), list(ys))


    matplot(xs, res, col="purple", type="l", lwd=3, xlab="x", ylab="pdf")

Displays

enter image description here

user9802913
  • 245
  • 4
  • 20