Correlation
By default, R offers the command cor()
that can compute Pearson's r (the default), Spearman's rho or Kendall's tau. It does not compute tests of significance, and it does not give detailed information about the number of cases used. Options are available for dealing with missing values. See section on options below on this and other topics.
The basic command
The command
offers two basic varieties: cor(x)
will compute correlations between all variables in (matrix) x
, whereas cor(x, y)
will compute correlations between all variables in (vector or matrix) x
and all variables in (vector or matrix) y
.
A Pearson correlation, thus, may easily be computed between two variables:
cor(my.data$var1, my.data$var2)
It is more difficult to obtain correlations between several variables, unless (a) you want correlations between all variables in your dataset and (b) the dataset contains only numeric variables. In this case the command is simply:
cor(my.data)
If your data do not meet this requirement, you may create a matrix (several columns) from your data. This may be achieved, e.g., like this:
cor(cbind(my.data$var1, my.data$var2, my.data$var3, my.data$var4))
You may also create two sets of variables, i.e. matrices; correlations will be computed between the variables from the two sets:
cor(cbind(my.data$var1, my.data$var2), cbind(my.data$var3, my.data$var4))
Spearman's and/or Kendall's correlations are available as follows:
cor(my.data$var1, my.data$var2, method = c("pearson", "kendall", "spearman"))
Delete as appropriate!
Options
The most important issue is perhaps how to deal with missing data; by default, you will get no results when missing data are present. In the case of correlation, the use
option has to be deployed, as in:
cor(my.data$var1, my.data$var2, use = "complete.obs" )
Here, correlation is computed only from cases with data in both variables. For pairwise case deletion (in the case of more than two variables), use use = "pairwise.complete.obs"
© W. Ludwig-Mayerhofer, R Guide | Last update: 20 Sep 2016