0

Is it possible to create a correlation matrix like in the image below using knitr() or similar?

enter image description here

for

res <- cor(iris[,1:4])
firmo23
  • 7,490
  • 2
  • 38
  • 114

1 Answers1

1

The scipub package has a function, correltable, to produce correlation tables with significance stars. You need to install the htmlTable package to have the possibility to get these correlation tables in HTML.

Is it what you want?

enter image description here

---
title: "Correlation table"
author: "Stéphane Laurent"
date: "17/01/2022"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(scipub)
library(mvtnorm)
set.seed(666L)
```

```{r}
dat <- as.data.frame(rmvnorm(50, sigma = toeplitz(3:1)))
colnames(dat) <- c("V1", "V2", "V3")
```

```{r, results='asis'}
correltable(dat, html = TRUE)
```

EDIT

To add the means and the standard deviations:

enter image description here

---
title: "Correlation table"
author: "Stéphane Laurent"
date: "17/01/2022"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(scipub)
library(htmlTable)
library(magrittr)
library(mvtnorm)
set.seed(666L)
```

```{r}
dat <- as.data.frame(rmvnorm(50, sigma = toeplitz(3:1)))
colnames(dat) <- c("V1", "V2", "V3")
cortable <- correltable(dat, html = FALSE)
table2 <- as.data.frame(matrix(as.character(cortable$table), nrow = 3)) 
caption <- cortable[["caption"]]
Means <- formatC(colMeans(dat))
Sds <- formatC(apply(dat, 2L, sd))
table1 <- data.frame(Mean = Means, SD = Sds)
```

```{r, results='asis'}
css.cell <- matrix("padding: 5px;", ncol = 6L, nrow = 4L)
css.cell[, 1L] <- 
  paste(css.cell[, 1L], "font-weight: bold;") # <-- bold row names
cbind(table1, table2) %>%
  addHtmlTableStyle(css.cell = css.cell) %>% 
  htmlTable(caption = caption)
```
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • I have an issue with knitting here https://stackoverflow.com/questions/70799722/display-correlation-matrix-in-word-document-using-knitr – firmo23 Jan 21 '22 at 10:19