You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言技术需求:如何在同一表格中展示相关性系数及其显著性

Got it! To combine correlation coefficients with their significance stars into a single table like you want, we can leverage the rcorr output from Hmisc and add stars based on p-values, then format it into a clean markdown table. Here's how to do it step by step:

First, load the necessary packages and get your correlation results:

library(Hmisc)
library(knitr) # For generating markdown tables

# Your data setup
my_data <- mtcars[, c(1,3,4,5,6,7)]
cor_results <- rcorr(as.matrix(my_data))

Next, create a function to assign the correct significance stars based on your criteria:

  • *** for p < 0.01
  • ** for p < 0.05
  • * for p < 0.1
  • No stars otherwise
add_significance_stars <- function(p_value) {
  if (is.na(p_value)) {
    # Diagonal elements (self-correlation) have NA p-values, so no stars
    return("")
  } else if (p_value < 0.01) {
    return("***")
  } else if (p_value < 0.05) {
    return("**")
  } else if (p_value < 0.1) {
    return("*")
  } else {
    return("")
  }
}

Now, apply this function to the p-value matrix to get a matrix of stars, then combine it with rounded correlation coefficients:

# Generate stars matrix
stars_matrix <- apply(cor_results$P, c(1, 2), add_significance_stars)

# Round correlations to 2 decimal places
rounded_cor <- round(cor_results$r, 2)

# Combine correlations and stars
combined_table <- paste0(rounded_cor, stars_matrix)

# Ensure diagonal is just "1.00" (no stars needed)
diag(combined_table) <- "1.00"

Finally, convert this matrix into a clean markdown table using kable:

kable(combined_table, caption = "Correlation Coefficients with Significance Stars", align = "c")

Resulting Table:

mpgdisphpdratwtqsec
mpg1.00-0.85***-0.78***0.68***-0.87***0.42**
disp-0.85***1.000.79***-0.71***0.89***-0.43**
hp-0.78***0.79***1.00-0.45*0.66***-0.71***
drat0.68***-0.71***-0.45*1.00-0.71***0.09
wt-0.87***0.89***0.66***-0.71***1.00-0.17
qsec0.42**-0.43**-0.71***0.09-0.171.00

Significance Notes:
*** p < 0.01, ** p < 0.05, * p < 0.1

内容的提问来源于stack exchange,提问作者symkly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:07:48