SavoyTruffle
SavoyTruffle

Reputation: 1

How to calculate covariance using apply function in R?

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.

Upvotes: 0

Views: 343

Answers (3)

Anakin
Anakin

Reputation: 1

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

Upvotes: 0

sebastiann
sebastiann

Reputation: 163

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?

Upvotes: 1

GuedesBF
GuedesBF

Reputation: 9858

We need mapply() here.

mapply(cov, list(X, Y))

Upvotes: 0

Related Questions