R 编程中的协方差和相关性
协方差和相关性是统计学中用来衡量两个随机变量之间关系的术语。这两个术语都测量一对随机变量或双变量数据之间的线性相关性。
在本文中,我们将讨论 R 中的cov() 、 cor()和cov2cor()函数,它们使用统计和概率论的协方差和相关方法。
R 编程语言中的协方差
在 R 编程中,可以使用cov()函数测量协方差。协方差是一个统计术语,用于衡量数据向量之间的线性关系的方向。数学上,
在哪里,
x represents the x data vector
y represents the y data vector
[Tex]\bar{x} [/Tex]represents mean of x data vector
[Tex]\bar{y} [/Tex]represents mean of y data vector
N represents total observations
R中的协方差语法
Syntax: cov(x, y, method)
where,
- x and y represents the data vectors
- method defines the type of method to be used to compute covariance. Default is “pearson”.
例子:
R
# Data vectors
x <- c(1, 3, 5, 10)
y <- c(2, 4, 6, 20)
# Print covariance using different methods
print(cov(x, y))
print(cov(x, y, method = "pearson"))
print(cov(x, y, method = "kendall"))
print(cov(x, y, method = "spearman"))
R
# Data vectors
x <- c(1, 3, 5, 10)
y <- c(2, 4, 6, 20)
# Print correlation using different methods
print(cor(x, y))
print(cor(x, y, method = "pearson"))
print(cor(x, y, method = "kendall"))
print(cor(x, y, method = "spearman"))
R
# Data vectors
x <- rnorm(2)
y <- rnorm(2)
# Binding into square matrix
mat <- cbind(x, y)
# Defining X as the covariance matrix
X <- cov(mat)
# Print covariance matrix
print(X)
# Print correlation matrix of data
# vector
print(cor(mat))
# Using function cov2cor()
# To convert covariance matrix to
# correlation matrix
print(cov2cor(X))
输出:
[1] 30.66667
[1] 30.66667
[1] 12
[1] 1.666667
R 编程语言中的相关性
R 编程中的cor()函数测量相关系数值。相关性是统计学中的一个关系术语,它使用协方差方法来衡量向量的相关程度。数学上,
在哪里,
x represents the x data vector
y represents the y data vector
[Tex]\bar{x} [/Tex]represents mean of x data vector
[Tex]\bar{y} [/Tex]represents mean of y data vector
R中的相关性
Syntax: cor(x, y, method)
where,
- x and y represents the data vectors
- method defines the type of method to be used to compute covariance. Default is “pearson”.
例子:
R
# Data vectors
x <- c(1, 3, 5, 10)
y <- c(2, 4, 6, 20)
# Print correlation using different methods
print(cor(x, y))
print(cor(x, y, method = "pearson"))
print(cor(x, y, method = "kendall"))
print(cor(x, y, method = "spearman"))
输出:
[1] 0.9724702
[1] 0.9724702
[1] 1
[1] 1
将协方差转换为 R 中的相关性
R 编程中的cov2cor()函数将协方差矩阵转换为相应的相关矩阵。
Syntax: cov2cor(X)
where,
- X and y represents the covariance square matrix
例子:
R
# Data vectors
x <- rnorm(2)
y <- rnorm(2)
# Binding into square matrix
mat <- cbind(x, y)
# Defining X as the covariance matrix
X <- cov(mat)
# Print covariance matrix
print(X)
# Print correlation matrix of data
# vector
print(cor(mat))
# Using function cov2cor()
# To convert covariance matrix to
# correlation matrix
print(cov2cor(X))
输出:
x y
x 0.0742700 -0.1268199
y -0.1268199 0.2165516
x y
x 1 -1
y -1 1
x y
x 1 -1
y -1 1