如何在R中制作符合APA格式的相关系数表
Perfect, let's build that APA-compliant correlation table in R exactly how you need it. I'll walk you through a step-by-step solution with code that's easy to adapt to your data:
Step 1: Calculate Correlations & P-Values
First, we'll use the psych package to compute both correlation coefficients and their corresponding p-values (it's more straightforward than base R for this task). We'll use sample data from mtcars here—just replace it with your own dataset.
# Load required package library(psych) # Replace this with your actual dataset my_data <- mtcars[, c("mpg", "disp", "hp", "wt")] # Compute Pearson correlations and p-values (use method = "spearman" for rank correlations) cor_results <- corr.test(my_data, method = "pearson") cor_matrix <- cor_results$r # Correlation coefficients p_matrix <- cor_results$p # P-values for significance
Step 2: Keep Only Lower (or Upper) Triangle
We'll zero out the upper triangle and diagonal (since APA tables typically only show one half of the correlation matrix to avoid redundancy). If you want the upper triangle instead, just swap upper.tri() with lower.tri().
# Keep only lower triangle (set upper triangle + diagonal to NA) lower_tri_cor <- cor_matrix lower_tri_cor[upper.tri(lower_tri_cor, diag = TRUE)] <- NA # For upper triangle instead: # upper_tri_cor <- cor_matrix # upper_tri_cor[lower.tri(upper_tri_cor, diag = TRUE)] <- NA
Step 3: Format Coefficients (2 Decimals, No Leading Zero)
We'll create a helper function to format the correlation values: it rounds to 2 decimals and removes the leading zero (e.g., 0.25 becomes .25, -0.05 becomes -.05).
# Helper function to format correlation values format_cor <- function(x) { if (is.na(x)) return("") # Leave empty cells for unused triangle # Round to 2 decimals formatted <- sprintf("%.2f", x) # Remove leading zero for positive values, adjust for negatives formatted <- gsub("^0\\.", "\\.", formatted) formatted <- gsub("^-0\\.", "-\\.", formatted) return(formatted) } # Apply formatting to our triangle matrix formatted_cors <- matrix(sapply(lower_tri_cor, format_cor), nrow = nrow(lower_tri_cor)) # Keep original column/row names colnames(formatted_cors) <- colnames(cor_matrix) rownames(formatted_cors) <- rownames(cor_matrix)
Step 4: Add Significance Stars
Next, we'll map p-values to APA-style significance stars:
*for p < 0.05**for p < 0.01***for p < 0.001
# Helper function to add stars based on p-value add_stars <- function(cor_val, p_val) { if (is.na(p_val)) return(cor_val) # Skip empty cells stars <- "" if (p_val < 0.001) stars <- "***" else if (p_val < 0.01) stars <- "**" else if (p_val < 0.05) stars <- "*" return(paste0(cor_val, stars)) } # Combine formatted correlations with significance stars final_table <- matrix(mapply(add_stars, formatted_cors, p_matrix), nrow = nrow(formatted_cors)) colnames(final_table) <- colnames(formatted_cors) rownames(final_table) <- rownames(formatted_cors)
Step 5: Output as Markdown Table
Finally, convert the matrix to a clean markdown table (great for reports, papers, or copy-pasting into documents) using the knitr package:
# Load knitr for markdown table output library(knitr) # Generate markdown table with caption kable(final_table, align = "c", caption = "Pearson Correlations (Lower Triangle, APA Format)")
Example Output
For the mtcars sample data, the output will look like this:
| mpg | disp | hp | wt | |
|---|---|---|---|---|
| mpg | ||||
| disp | -.85*** | |||
| hp | -.78*** | .79*** | ||
| wt | -.87*** | .89*** | .66*** |
Quick Adjustments
- To use upper triangle instead of lower: Swap the triangle logic in Step 2
- For Spearman/Kendall correlations: Change
method = "spearman"ormethod = "kendall"in Step 1 - To adjust significance thresholds: Modify the p-value cutoffs in the
add_starsfunction
内容的提问来源于stack exchange,提问作者Ehsan88

