如何停止 R 中 Spearman Rho 相关性 table 中的重复相关性?

How to stop duplicate correlations in table of Spearman Rho correlations in R?

我使用以下代码为 R 中包含 2+ 列的 CSV 文件制作了 table Spearman Rho 相关:

> myDataset <- read.csv(file.choose())
> attach(myDataset)
> spearmanRhoTestData <- cor(myDataset, use="complete.obs",method="spearman")

然而,在我的 table (spearmanRhoTestData) 中,任意两个变量之间的相关性将出现两次(如下所示):

    Var1 Var2 Var3 Var4
Var1  1   0.5  0.7 0.9
Var2  0.5  1   0.3 0.6  
Var3  0.7  0.3  1  0.2
Var4  0.9  0.6  0.2 1

有什么方法可以让我在 R 中编写代码以消除相关值(例如:var1 和 var2 之间)在整个 table 中出现两次??

假设您想保留相关矩阵格式的最简单方法是

# set upper triangle values to NA
spearmanRhoTestData[upper.tri(spearmanRhoTestData)] = NA

# visualise updated matrix
spearmanRhoTestData

这是另一种方法,使用 corrr 包,它会给你一个重塑的相关数据框,没有重复:

library(corrr)

# get correaltion matrix
tbl = correlate(mtcars)

# set upper triangle values to NA
tbl[upper.tri(tbl)] = NA

# reshape and omit NAs
stretch(tbl, na.rm = T)

# # A tibble: 55 x 3
#     x     y     r
#  <chr> <chr>  <dbl>
# 1 mpg   cyl   -0.852
# 2 mpg   disp  -0.848
# 3 mpg   hp    -0.776
# 4 mpg   drat   0.681
# 5 mpg   wt    -0.868
# 6 mpg   qsec   0.419
# 7 mpg   vs     0.664
# 8 mpg   am     0.600
# 9 mpg   gear   0.480
# 10 mpg   carb  -0.551
# # ... with 45 more rows