Introduction
Correlation measures the strength and direction of the relationship between two variables.
Correlation Functions
# Pearson correlation
cor(x, y)
# Spearman correlation
cor(x, y, method = "spearman")
# Kendall correlation
cor(x, y, method = "kendall")
Correlation Matrix
# Matrix for data frame
cor(df)
# Using dplyr
library(dplyr)
df %>%
select_if(is.numeric) %>%
cor()
Correlation Test
# Test correlation
cor.test(x, y)
# With method
cor.test(x, y, method = "spearman")
# Partial correlation
library(ppcor)
pcor.test(x, y, z)
Visualization
# Correlation plot
library(corrplot)
corrplot(cor_matrix)
# Heatmap
library(ggplot2)
ggplot(data, aes(x = x, y = y)) +
geom_tile(aes(fill = correlation))
Summary
Correlation measures linear relationships. Use appropriate method based on data characteristics.