Skip to content

Instantly share code, notes, and snippets.

@neilkod
Created September 17, 2010 10:32
Show Gist options
  • Save neilkod/584034 to your computer and use it in GitHub Desktop.
Save neilkod/584034 to your computer and use it in GitHub Desktop.
covariance matrix in R
define x and y
x<-c(2.5,.5,2.2,1.9,3.1,2.3,2,1,1.5,1.1)
y<-c(2.4,.7,2.9,2.2,3.0,2.7,1.6,1.1,1.6,.9)
create a covariance matrix the hard way
cm<-matrix(data=c(cov(x,x),cov(x,y),cov(y,x),cov(y,y)),nrow=2,ncol=2)
> cm
[,1] [,2]
[1,] 0.6165556 0.6154444
[2,] 0.6154444 0.7165556
>
edit: thanks to @johnmyleswhite (as usual), here is the solution:
http://twitter.com/johnmyleswhite/status/24749000734
@neilkod In general, lots of the single vector functions work on data frames in a sensible way.
http://twitter.com/johnmyleswhite/status/24748937928
@neilkod cov(data.frame(x, y))
> cov(data.frame(x,y))
x y
x 0.6165556 0.6154444
y 0.6154444 0.7165556
> data.frame(x,y)
x y
1 2.5 2.4
2 0.5 0.7
3 2.2 2.9
4 1.9 2.2
5 3.1 3.0
6 2.3 2.7
7 2.0 1.6
8 1.0 1.1
9 1.5 1.6
10 1.1 0.9
>
@hadley
Copy link

hadley commented Sep 17, 2010

This is a case where you probably actually should use cbind: cov(cbind(x, y))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment