Home > Mobile >  How to calculate covariance using apply function in R?
How to calculate covariance using apply function in R?

Time:10-02

I'm trying to simulate two distributions and compare their covariance using two functions. But when defining my covariance functions, I run into an arrow:

Error in apply(c(X, Y), 1, cov) : dim(X) must have a positive length

This is my code so far:

X <- matrix(rnorm(30,0,2))
Y <- matrix(rnorm(30,2,3))

S2 <- apply(c(X,Y), 1, cov)

Thank you in advance.

CodePudding user response:

I am not really sure, what your final goal really is giving X and Y.

But maybe cov(cbind(X,Y)) is doing what you expect?

CodePudding user response:

We need mapply() here.

mapply(cov, list(X, Y))

CodePudding user response:

Try sapply(list(X, Y), cov), sapply() takes a list, vector as input and the output is a vector.

  • Related