0
votes

I'm creating a (apa) table with specific correlations from a bigger matrix, I also want to add an asterisk if the correlation is significant. I used the Hmisc package to create all possible correlations and corresponding p-values. Then I used the MOTE package to round the correlations and get rid of leading zeros. Then I changed the p-values into asterisks. I pulled out those correlations of interest and put them in a new matrix. Let's say that I only want to create a new correlation matrix (3 by 4) with 'am', 'gear' and 'carb' defining the 3 rows and 'mpg', 'cyl', 'disp' and 'hp' defining the 4 columns.

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

After this, I got stuck. Now I would like to add the appropriate number of asterisks to each cell (behind the values for the correlations), and if possible, have everything nicely vertically aligned. Dots for decimal place vertically above each other, maybe this is something i need to do in rmarkdown, but I haven't got that far yet). Of course, if there's an easier - or more elegant way - to get all this done, i'm all ears. Thank you.

1

1 Answers

0
votes

Found a solution to most important part, extracting specific pairwise correlations and add the appropiate number of asterisks for their significance level (no solution yet for vertically aligning values according to the decimal point and making asterisks appear smaller):

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***"