R语言 协方差和相关性

R语言 协方差和相关性

协方差相关 是统计学中用来衡量两个随机变量之间关系的术语。这两个术语都衡量一对随机变量或双变量数据之间的线性依赖关系。

在这篇文章中,我们将讨论R语言中的 cov()cor()cov2cor() 函数,这些函数使用统计学和概率论的协方差和相关方法。

R编程语言中的协方差

在R编程中,协方差可以用 cov() 函数来测量。协方差是一个统计术语,用于测量数据向量之间的线性关系的方向。在数学上,

R编程中的协方差和相关性

其中

x 代表x数据向量

y 代表y数据向量

N 代表总观测值

R语言中的协方差语法

语法: cov(x, y, method)

其中

  • xy 代表数据向量
  • method 定义了用于计算协方差的方法类型。默认为 “pearson”。

例子

# 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

输出

[1] 30.66667
[1] 30.66667
[1] 12
[1] 1.666667
R

R编程语言中的相关关系

R编程中的 cor() 函数测量相关系数值。相关性是统计学中的一个关系术语,它使用协方差方法来衡量向量之间的关系有多强。在数学上,

R编程中的协方差和相关性

其中

x 代表x数据向量

y 代表y数据向量

R语言中的相关关系

语法: cor(x, y, method)

其中

  • xy 代表数据向量
  • method 定义了用于计算协方差的方法的类型。默认为 “pearson”。

例子

# 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

输出

[1] 0.9724702
[1] 0.9724702
[1] 1
[1] 1
R

R语言中的协方差转换为相关关系

R编程中的 cov2cor() 函数将协方差矩阵转换为相应的相关矩阵。

语法: cov2cor(X)

其中

  • Xy 代表协方差平方矩阵

例子

# 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))
R

输出

           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
R

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册