Rev 9615 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
\name{cor}\title{Correlation, Variance and Covariance (Matrices)}\usage{var(x, y = NULL, na.rm = FALSE, use)cor(x, y = NULL, use = "all.obs")cov(x, y = NULL, use = "all.obs")}\alias{var}\alias{cor}\alias{cov}\description{\code{var}, \code{cov} and \code{cor} compute the variance of \code{x}and the covariance or correlation of \code{x} and \code{y} if theseare vectors. If \code{x} and \code{y} are matrices then thecovariance (correlation) between the columns of \code{x} and thecolumns of \code{y} are computed.}\arguments{\item{x}{a numeric vector, matrix or data frame.}\item{y}{\code{NULL} (default) or a vector, matrix or data frame withcompatible dimensions to \code{x}. The default is equivalent to\code{y = x} (but more efficient).}\item{use}{an optional character string giving amethod for computing covariances in the presenceof missing values. This must be (an abbreviation of) one of the strings\code{"all.obs"}, \code{"complete.obs"} or \code{"pairwise.complete.obs"}.}}\details{\code{var} is just another interface to \code{cov}, where\code{na.rm} is used to determine the default for \code{use} when thatis unspecified. If \code{na.rm} is \code{TRUE} then the completeobservations (rows) are used (\code{use = "complete"}) to compute thevariance. Otherwise (\code{use = "all"}), \code{var} will give anerror if there are missing values.If \code{use} is \code{"all.obs"}, then the presenceof missing observations will produce an error.If \code{use} is \code{"complete.obs"} then missing valuesare handled by casewise deletion. Finally, if \code{use} has thevalue \code{"pairwise.complete.obs"} then the correlation betweeneach pair of variables is computed using all complete pairsof observations on those variables.This can result in covariance or correlation matrices which are notpositive semidefinite.The denominator \eqn{n - 1} is used which gives an unbiased estimatorof the (co)variance for i.i.d. observations.These functions return \code{\link{NA}} when there is only one observation.}\seealso{\code{\link{cov.wt}} for \emph{weighted} covariance computation.}\examples{var(1:10)# 9.166667var(1:5,1:5)# 2.5## Two simple vectorscor(1:10,2:11)# == 1## var() & cov() are "really the same":stopifnot(var(1:5,0:4) == cov(1:5))\testonly{stopifnot(is.na(var(1)) && !is.nan(var(1)))}## Correlation Matrix of Multivariate sample:data(longley)(Cl <- cor(longley))## Graphical Correlation Matrix:symnum(Cl) # highly correlated##--- Missing value treatment:data(swiss)C1 <- cov(swiss)range(eigen(C1, only=TRUE)$val) # 6.19 1921swiss[1,2] <- swiss[7,3] <- swiss[25,5] <- NA # create 3 "missing"\dontrun{C2 <- cov(swiss) # Error: missing obs...}C2 <- cov(swiss, use = "complete")range(eigen(C2, only=TRUE)$val) # 6.46 1930C3 <- cov(swiss, use = "pairwise")range(eigen(C3, only=TRUE)$val) # 6.19 1938}\keyword{univar}\keyword{multivariate}\keyword{array}