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

时间:2018-03-04 19:56:48

标签: r matrix correlation p-value significance

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

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中做的事情,但我还没有那么远)。当然,如果有一个更容易   - 或更优雅的方式 - 完成所有这些,我都是耳朵。谢谢。

1 个答案:

答案 0 :(得分: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***"