【问题标题】:How print Pearson correlation matrix to Word in r如何在 r 中将 Pearson 相关矩阵打印到 Word
【发布时间】:2021-07-15 18:07:28
【问题描述】:

我对 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)
}

最后我绘制表格并导出到 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)。

提前谢谢..

【问题讨论】:

  • 你可以直接用xlsx(to write excel)包来写。不确定是否有一些直接用于 docx 扩展的功能,但是在编写 excel 表后,将其移动到任何其他办公文件会更容易
  • 谢谢@SametSökel,我认为很难找到我要找的东西,希望有人知道一种方法,可以像“.docx”或“html”中的“stargazer”那样打印,以便直接放入文档,无需进一步的步骤。
  • 如果您正在使用 R Studio,您可以直接将您的笔记本导出为 html 页面。您可以更喜欢在 R 中打印,然后将您的笔记本编织为 html

标签: r export correlation


【解决方案1】:

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

library(modelsummary)

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

【讨论】:

    猜你喜欢
    • 2019-04-22
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 2020-04-12
    • 2019-12-07
    相关资源
    最近更新 更多