从相关矩阵中提取特定的成对相关性,并为相应的显着性水平添加适当数量的星号

问题描述 投票:0回答:1

我正在从一个更大的矩阵创建一个具有特定相关性的(apa)表,如果相关性很大,我还想添加一个星号。我使用Hmisc包来创建所有可能的相关性和相应的p值。然后我使用MOTE包来舍入相关性并摆脱前导零。然后我将p值更改为星号。我把那些感兴趣的相关性拉出来并把它们放在一个新的矩阵中。假设我只想创建一个新的相关矩阵(3乘4),其中'am','gear'和'carb'定义3行,'mpg','cyl','disp'和'hp'定义4列。

library(Hmisc) # to get correlations and p-values

cormat = rcorr(as.matrix(mtcars))
cormat$r # to see the correlations
cormat$P # to see the p-values


cor.table = matrix(NA, nrow = 3, ncol = 4) # create empty matrix

library(MOTE) # to round and get rid of leading 0's

cor.table[1:3,1:4] = c(apa(cormat$r[9:11, c(1:4)],2,F)) # fill with correlations and get rid of leading zero's

pm = ifelse(cormat$P <= .001, "***", 
        ifelse(cormat$P <= .01, "**", 
           ifelse(cormat$P <= .05, "*", " "))) # create the appr. number of asterisks per cell

在此之后,我被困住了。现在我想为每个单元格添加适当数量的星号(在相关值的后面),如果可能的话,让所有内容都很好地垂直对齐。小数点垂直位于彼此之上,也许这是我需要在rmarkdown中做的事情,但我还没有那么远)。当然,如果有一个更容易 - 或更优雅的方式 - 完成所有这些,我都是耳朵。谢谢。

r matrix correlation p-value significance
1个回答
0
投票

找到最重要部分的解决方案,提取特定的成对相关性,并为其显着性水平添加适当数量的星号(没有解决方案根据小数点垂直对齐值并使星号显得更小):

library(Hmisc)                    # to get correlations and p-values

cormat = rcorr(as.matrix(mtcars))
cormat$r                          # to see all correlations
cormat$P                          # to see the p-values

cor.table = matrix(NA, nrow = 3, ncol = 4) # create empty matrix


library(MOTE)                     # to round and get rid of leading 0's

pm = ifelse(cormat$P <= .001, "***", 
        ifelse(cormat$P <= .01, "**", 
           ifelse(cormat$P <= .05, "*", " "))) # create the appr. number of asterisks per cell


cor.table = matrix(NA, 
                   nrow = 3, 
                   ncol = 4) # create empty matrix

cor.table[1:3,1:4] = paste(
  apa(cormat$r[9:11, 1:4], 2,F),
  pm[9:11, 1:4],
  sep = ""
  )

cor.table  # to see resulting matrix

#      [,1]     [,2]     [,3]      [,4]    
# [1,] ".60***" "-.52**" "-.59***" "-.24 " 
# [2,] ".48**"  "-.49**" "-.56***" "-.13 " 
# [3,] "-.55**" ".53**"  ".39*"    ".75***"
© www.soinside.com 2019 - 2024. All rights reserved.