I am a relative newbie in R. I want to create a correlation matrix ready for publication (in a word document). I want the matrix to show the correlations and stars for significance.
Here is what I did so far:
library(flextable)
library(psych)
# Creating data frame
var1 <- c(2,3,1,5,4,5)
var2 <- c(23,25,21,31,67,43)
var3 <- c(2,5,98,4,3,54)
df <- data.frame(var1,var2,var3)
#running correlation with psych package
df.corr <- psych::corr.test(df, adjust = "none")
# create correlation table with flextable package.
inter_corr_r <- as.data.frame(df.corr$r) # changing to data frame.
ft.corr <-flextable(inter_corr_r) %>%
colformat_double(
digits = 2
)
ft.corr
Here is the results:
Missing is the first column with the names of the variables and the significant stars. If easier and better, a solution using gtsummary can be suitable too.
One option would be to use the already formatted stars
table returned as an element of the corr.test
object and add the row names manually:
library(flextable)
library(psych)
# Creating data frame
var1 <- c(2, 3, 1, 5, 4, 5)
var2 <- c(23, 25, 21, 31, 67, 43)
var3 <- c(2, 5, 98, 4, 3, 54)
df <- data.frame(var1, var2, var3)
df.corr <- psych::corr.test(df, adjust = "none")
inter_corr_r <- df.corr$stars
inter_corr_r <- cbind(var = rownames(inter_corr_r), inter_corr_r)
inter_corr_r <- as.data.frame(inter_corr_r)
ft.corr <- flextable(inter_corr_r) |>
set_header_labels(var = "")
ft.corr