如何在 r 中将 Pearson 相关矩阵打印到 Word

How print Pearson correlation matrix to Word in r

我是 R 的新手,我想在 word 文档中绘制一个奇特的相关矩阵。

这里是我的数据的一个小例子:

provaSO1 <- structure(list(TotalDebt = c(0.637, 0.517, 0.581, 0.785, 0.687,0.703, 0.474), 
               Long_ok = c(0.157, 0.121, 0.051, 0.29, 0.153,0.301, 0.102), 
               Short_ok = c(0.48, 0.396, 0.531, 0.495, 0.535,0.402, 0.372), 
               Size = c(6.184, 6.184, 6.663, 7.302, 6.714, 6.949,7.627), 
               ln_Age = c(3.638, 3.664, 3.689, 3.714, 3.738, 3.761, 3.784), 
               liquidity = c(0.99, 0.988, 0.995, 0.965, 0.949, 0.949,0.53),
               Asset_Tangibility = c(0.005, 0.006, 0.003, 0.023, 0.033, 0.03, 0.457), 
               profitability = c(-0.058, -0.202, -0.106, 0.032, 0.03, 0.013, 0.042)), 
          row.names = c(NA, 7L), class = "data.frame")

首先我要计算相关矩阵:

c_matrix = cor(provaSO1, method = c("pearson"))

我使用 corstars function 添加显着性水平并仅获得下三角:

corstarsl <- function(x){
  require(Hmisc)
  x <- as.matrix(x)
  R <- rcorr(x)$r
  p <- rcorr(x)$P

 mystars <- ifelse(p < .001, "***", ifelse(p < .01, "** ", ifelse(p < .05, "* ", " ")))

 R <- format(round(cbind(rep(-1.11, ncol(x)), R), 3))[,-1]

 Rnew <- matrix(paste(R, mystars, sep=""), ncol=ncol(x))
  diag(Rnew) <- paste(diag(R), " ", sep="")
  rownames(Rnew) <- colnames(x)
  colnames(Rnew) <- paste(colnames(x), "", sep="")

 Rnew <- as.matrix(Rnew)
  Rnew[upper.tri(Rnew, diag = TRUE)] <- ""
  Rnew <- as.data.frame(Rnew)
 
  Rnew <- cbind(Rnew[1:length(Rnew)-1])
  return(Rnew)
}

最后我绘制了 table 并导出到 excel:

matrix_correlation <- corstarsl(provaSO1)

library(xtable)
corr_print <- xtable(matrix_correlation)

library(rio) 
library(openxlsx)
export(corr_print,"correlation_ok.xlsx")

我想知道是否有更优雅的方法来打印 Pearson 相关矩阵并放入 Word 文档(例如用于回归的 Stargazer tables)。

提前致谢..

您可以使用 modelsummary package for R 将关联 table 直接保存到 Word 文档。 (免责声明:我是作者。)使用 datasummary_correlation 函数及其 output 参数,我们有:

library(modelsummary)

datasummary_correlation(provaSO1,
                        output = "correlation_table.docx")