1

I want to turn an intervariable correlations table in R to a table formatted according to APA styles. The table should have the following characteristics

  • Have only lower or upper diagonal of the matrix
  • Usually display correlation coefficients only with 2 decimals and no leading zeros e.g. .25, -.05
  • Denote significance by e.g. a number of stars
Ehsan88
  • 3,569
  • 5
  • 29
  • 52
  • does this help: https://stackoverflow.com/questions/44267088/using-apatables-or-apastyles-packages-with-knitr or have a look at [papaya](https://github.com/crsh/papaja/blob/master/example/example.Rmd) – Tom Apr 09 '18 at 15:46

1 Answers1

2

I used Hmisc to create correlation table with p-values but this is doable without the package, especially if you want Kendall's tau correlations.

#First indicate which columns do you want in your correlation table
cor_cols = c('gender','age','education','expense',
              'learningmotivation', 'reading')


#Slice the data and calculate correlation table:
mt = as.matrix(data[,cor_cols])
library(Hmisc)
myrcorr <- rcorr(mt, type="spearman")

#format numbers
cor_table <-as.matrix( round(myrcorr$r,2))

#remove rownames and colnames
colnames(cor_table)<- rownames(cor_table)<- NULL

#remove leading zeros and add stars
n <- length(cor_cols)
for (c in 1:n) {
  for (r in 1:n) {
      pval <- myrcorr$P[r,c]
      stars <- ifelse(pval < .001, "***", ifelse(pval < .01, "** ", ifelse(pval < .05, "*  ", "   ")))
      coeff = sub("0*\\.",".",cor_table[r,c]) #remove leading zeros
      cor_table[r,c] = paste(c(coeff,stars),collapse='')
  }
}

cor_table[upper.tri(cor_table)] <- '' # erase the upper triangle
diag(cor_table) <- '-' # replace the diagonals by dash(-)
Ehsan88
  • 3,569
  • 5
  • 29
  • 52