The “cor” Function in R
Package: Base R (no specific package required)
Purpose: Computes the correlation coefficient between two or more vectors.
General Class: Statistical Analysis
Required Argument(s):
x: A numeric vector, matrix, or data frame.
y: If x is a matrix or data frame, y is optional and can be another matrix or data frame. If x is a vector, y is ignored.
Notable Optional Arguments:
method: The correlation method to be used. Options include “pearson” (default), “kendall”, and “spearman”.
use: A character string indicating how to treat missing values. Options include “everything” (default), “all.obs”, “complete.obs”, and “na.or.complete”.
Example:
# Example data frame
data <- data.frame(
Height = c(160, 170, 165, 175, 180),
Weight = c(55, 70, 60, 80, 75),
Age = c(25, 30, 35, 40, 45)
)
# Compute Pearson correlation matrix
result <- cor(data)
print(result)In this example, the cor function is used to compute the Pearson correlation matrix for the numeric variables Height, Weight, and Age in the data frame. The result is then printed to the console.