UK-based online statistics and data analysis support for USA, UK, and international clients. No exams, no impersonation, no fabricated data.

Linear association, correlation matrix, p-values, confidence intervals and Excel worked formulas

Pearson Correlation: Formula, Interpretation, Python, R, SPSS and Excel Guide

Pearson Correlation, also called the Pearson product-moment correlation coefficient or Pearson r, measures the strength and direction of a linear relationship between two quantitative variables. This guide explains Pearson r using a student performance dataset with 649 rows, 16 numeric variables and 120 pairwise correlations. The strongest pair is G2 and G3, with r = 0.918548, showing a very strong positive linear association between second-period grade and final grade.

Quick Answer: Pearson Correlation Result

The main Pearson Correlation analysis uses 16 numeric variables and 649 complete observations. The workbook calculates 120 pairwise Pearson correlations, including correlations with the main outcome variable G3 final grade.

The strongest absolute correlation is between G2 and G3. The Pearson correlation coefficient is r = 0.918548, which is a very strong positive linear association. The shared variance is r² = 0.843730, meaning approximately 84.37% of the variation in one variable is linearly shared with the other in this pairwise relationship.

Dataset rows649
Numeric variables16
Variable pairs120
Main outcomeG3

Strongest pairG2–G3
Pearson r0.9185
Shared variance84.37%
InterpretationVery strong

Final interpretation: G2 and G3 have a very strong positive Pearson correlation. Students with higher second-period grades tend to have higher final grades. This is a linear association result, not proof of causation.

Important reporting point: Pearson r measures linear association. Before reporting it, check linearity, outliers, approximate normality for inference and independence of observations. The uploaded workbook includes assumption diagnostics and outlier context for this reason.

Table of Contents

  1. What Is Pearson Correlation?
  2. When Should You Use Pearson Correlation?
  3. Pearson Correlation Formula
  4. Null and Alternative Hypotheses
  5. Dataset and Variables Used
  6. Descriptive Statistics and Assumption Diagnostics
  7. Verified Pearson Correlation Results
  8. Correlations with G3
  9. Strongest Pairwise Pearson Correlations
  10. Python Chart-by-Chart Interpretation
  11. R Chart-by-Chart Interpretation
  12. SPSS Output and Workflow Interpretation
  13. Excel Worked File Explanation
  14. Python, R, SPSS and Excel Workflows
  15. Code Blocks and Excel Formulas
  16. Pearson Correlation Assumptions
  17. How to Report Pearson Correlation
  18. Common Mistakes
  19. Downloads and Resources
  20. Related Statistical Guides
  21. FAQs About Pearson Correlation

What Is Pearson Correlation?

Pearson Correlation is a statistical measure that describes the strength and direction of a linear relationship between two quantitative variables. The coefficient is usually written as r. It ranges from -1 to +1. A value close to +1 means a strong positive linear relationship. A value close to -1 means a strong negative linear relationship. A value close to 0 means little or no linear relationship.

A positive Pearson correlation means that higher values of one variable tend to occur with higher values of the other variable. A negative Pearson correlation means that higher values of one variable tend to occur with lower values of the other variable. In this post, the strongest positive example is G2 with G3, where students with higher second-period grades tend to have higher final grades.

Pearson correlation is best understood visually with a scatterplot. If the points form an upward-sloping cloud, the correlation is positive. If the points form a downward-sloping cloud, the correlation is negative. If the points are widely scattered without a clear line-like pattern, Pearson r is near zero. The stronger and tighter the line-like pattern, the larger the absolute value of r.

This guide connects Pearson r with Correlation in Python, Correlation in R, Correlation in SPSS, Correlation in Excel, Correlation Matrix, Correlation Heatmap, Correlation Assumptions, Correlation vs Regression, p-value, effect size and confidence interval.

Simple definition: Pearson Correlation measures how closely two quantitative variables follow a straight-line relationship.

When Should You Use Pearson Correlation?

Use Pearson Correlation when both variables are numeric and the research question is about linear association. It is especially useful when you want to summarize the relationship between two continuous or quantitative variables with one coefficient.

SituationUse Pearson Correlation?Reason
Both variables are numericYesPearson r is designed for quantitative variables.
The scatterplot shows a roughly straight-line patternYesPearson r measures linear association.
You want a correlation matrix of several numeric variablesYesPearson matrices are common for exploratory analysis.
The variables are ordinal with strong tiesUse cautionSpearman or Kendall may be better for purely ordinal variables.
The relationship is curved or nonlinearUsually noPearson r may miss nonlinear association.
There are extreme influential outliersUse cautionOutliers can inflate or weaken Pearson r.
The goal is prediction or explanation with multiple predictorsNot by itselfUse regression after correlation screening.

In the student performance example, the main grade variables G1, G2 and G3 are numeric grade scores. Pearson correlation is therefore useful for studying their linear relationships. However, the workbook also includes outlier and distribution checks because variables such as failures, Dalc, absences and grade scores may contain skewness, repeated values or influential observations.

Pearson Correlation Formula

The Pearson correlation coefficient is calculated by comparing how two variables vary together relative to their individual variation.

r = Σ[(xᵢ − x̄)(yᵢ − ȳ)] / √[Σ(xᵢ − x̄)² Σ(yᵢ − ȳ)²]

In this formula, xᵢ and yᵢ are paired observations, is the mean of X, and ȳ is the mean of Y. The numerator measures how X and Y move together. The denominator standardizes that movement so the final coefficient is always between -1 and +1.

Formula ElementMeaningHow to Understand It
xᵢ − x̄Deviation of each X value from the X meanShows whether each X value is above or below average.
yᵢ − ȳDeviation of each Y value from the Y meanShows whether each Y value is above or below average.
Σ[(xᵢ − x̄)(yᵢ − ȳ)]Sum of paired cross-productsPositive when X and Y tend to rise together; negative when one rises as the other falls.
√[Σ(xᵢ − x̄)² Σ(yᵢ − ȳ)²]Standardizing denominatorScales the coefficient to the -1 to +1 range.
Shared varianceFor G2–G3, r² = 0.8437, meaning about 84.37% shared linear variance.

The significance test for Pearson r uses:

t = r √[(n − 2) / (1 − r²)]

The degrees of freedom are:

df = n − 2

For the strongest pair G2–G3, n = 649, r = 0.918548, df = 647, and the p-value is extremely small. In normal reporting, this is written as p < .001.

Null and Alternative Hypotheses

The Pearson correlation hypothesis test checks whether the population correlation is zero. For the strongest pair, the hypotheses are about the relationship between G2 and G3.

StatementHypothesisMeaning
Null hypothesisH0: ρ = 0There is no linear association between the two variables in the population.
Alternative hypothesisH1: ρ ≠ 0There is a nonzero linear association between the two variables.
Decision ruleReject H0 if p < .05The correlation is statistically significant.
Result for G2–G3r = 0.918548, p < .001Reject H0; very strong positive linear association.

Decision: The G2–G3 Pearson correlation is statistically significant. The practical strength is also very large because the coefficient is close to +1.

Dataset and Variables Used

The analysis uses the student performance dataset. The workbook selected 16 numeric variables for Pearson correlation. These variables include demographic, academic, lifestyle, attendance and grade variables.

No.VariableRoleReason Included
1ageNumeric analysis variableStudent age; used to check grade and behavior associations.
2MeduNumeric/ordinal education variableMother education level.
3FeduNumeric/ordinal education variableFather education level.
4traveltimeNumeric/ordinal variableTravel time category.
5studytimeNumeric/ordinal variableStudy time category.
6failuresNumeric/count-like variableNumber of past class failures.
7famrelNumeric/ordinal variableFamily relationship quality.
8freetimeNumeric/ordinal variableFree time after school.
9gooutNumeric/ordinal variableGoing out with friends.
10DalcNumeric/ordinal variableWeekday alcohol consumption.
11WalcNumeric/ordinal variableWeekend alcohol consumption.
12healthNumeric/ordinal variableCurrent health status.
13absencesNumeric count variableNumber of school absences.
14G1Grade variableFirst-period grade.
15G2Grade variableSecond-period grade.
16G3Main outcome gradeFinal grade and main outcome for correlation summaries.

Although Pearson correlation is a numeric method, some selected variables are ordinal-style numeric variables. This is common in educational examples, but it should be reported carefully. For purely ordinal interpretation, Spearman or Kendall methods may also be considered.

Descriptive Statistics and Assumption Diagnostics

The Excel workbook includes descriptive statistics and practical assumption diagnostics for each selected variable. These values help readers understand the scale, spread, skewness and possible outlier issues before interpreting Pearson r.

VariableNMeanStd. Dev.MinimumMedianMaximumSkewnessIQR Outliers
age64916.74421.21811517220.41681
Medu6492.51461.1346024-0.03000
Fedu6492.30661.09990240.21530
traveltime6491.56860.74871141.247616
studytime6491.93070.82951240.699635
failures6490.22190.59320033.0927100
famrel6493.93070.9557145-1.105951
freetime6493.18031.0511135-0.181345
absences6493.65954.640802322.020721
G164911.39912.745301119-0.002816
G264911.57012.913601119-0.360325
G364911.90603.230701219-0.912916

The grade variables are numeric and suitable for Pearson correlation, but the outlier and distribution checks still matter. For example, failures is heavily skewed because many students have zero failures. Absences is also skewed, with some higher absence counts. These are the types of variables where Pearson correlation should be interpreted along with scatterplots and outlier context.

Verified Pearson Correlation Results

The workbook dashboard identifies G2–G3 as the strongest absolute pair. This is the main result used for the strongest pair scatterplot and top correlation interpretation.

Result ItemValueInterpretation
Dataset rows649All selected variables have complete numeric values in the workbook.
Numeric variables16Variables included in the Pearson correlation matrix.
Pairwise correlations120All unique pairs among 16 variables.
Strongest absolute pairG2–G3Second-period grade and final grade.
Pearson r0.918548Very strong positive linear association.
R squared0.843730About 84.37% shared linear variance.
Approximate t statistic59.104Very large test statistic for H0: r = 0.
95% CI for r0.9056 to 0.9298The population correlation is estimated to be very high.
p-value< .001Statistically significant.
DecisionReject H0There is a significant positive linear association.

The strongest pair is expected because G2 and G3 are consecutive grade outcomes. G2 is the second-period grade and G3 is the final grade, so they measure closely related academic performance. The scatterplot should show a tight upward pattern, which is consistent with r = 0.918548.

Correlations with G3

Because G3 is the final grade, the workbook dashboard summarizes each selected variable’s Pearson correlation with G3. This section is useful for understanding which variables are most closely related to final grade.

VariablePearson r with G3DirectionPractical StrengthInterpretation
G20.918548PositiveVery strongSecond-period grade is the strongest correlate of final grade.
G10.826387PositiveVery strongFirst-period grade strongly predicts the final-grade pattern.
failures-0.393316NegativeModerateMore past failures are associated with lower final grades.
studytime0.249789PositiveWeakMore studytime is associated with slightly higher final grades.
Medu0.240151PositiveWeakHigher mother education is weakly associated with higher G3.
Fedu0.211800PositiveWeakHigher father education is weakly associated with higher G3.
Dalc-0.204719NegativeWeakHigher weekday alcohol consumption is associated with lower G3.
Walc-0.176619NegativeWeakHigher weekend alcohol consumption is associated with lower G3.
traveltime-0.127173NegativeWeakLonger travel time is weakly associated with lower G3.
freetime-0.122705NegativeWeakMore free time is weakly associated with lower G3.
age-0.106505NegativeWeakOlder students have a weak negative association with G3.
health-0.098851NegativeNegligibleHealth has a very small negative linear association with G3.
absences-0.091379NegativeNegligibleAbsences show a small negative association with final grade.
goout-0.087641NegativeNegligibleGoing out has a very small negative association with G3.
famrel0.063361PositiveNegligibleFamily relationship has little linear association with G3.

The most important pattern is that grade variables dominate the G3 correlations. G2 and G1 are far stronger than demographic, lifestyle or attendance variables. Failures is the strongest negative non-grade relationship with G3.

Strongest Pairwise Pearson Correlations

The full correlation matrix contains 120 unique variable pairs. The strongest pairs by absolute value are listed below.

RankPairPearson rR SquaredDirectionStrengthInterpretation
1G2–G30.9185480.843730PositiveVery strongSecond-period grade and final grade are strongly linearly connected.
2G1–G20.8649820.748193PositiveVery strongFirst-period and second-period grades move together strongly.
3G1–G30.8263870.682916PositiveVery strongFirst-period grade is strongly associated with final grade.
4Medu–Fedu0.6474770.419226PositiveStrongMother and father education levels are strongly related.
5Dalc–Walc0.6165610.380148PositiveStrongWeekday and weekend alcohol consumption move together.
6failures–G3-0.3933160.154697NegativeModerateMore failures are associated with lower final grades.
7goout–Walc0.3886800.151072PositiveModerateGoing out and weekend alcohol consumption are moderately related.
8failures–G2-0.3857820.148828NegativeModerateMore failures are associated with lower second-period grades.
9failures–G1-0.3842100.147618NegativeModerateMore failures are associated with lower first-period grades.
10freetime–goout0.3463520.119960PositiveModerateFree time and going out are moderately related.

This table shows that Pearson correlation can reveal both academic and lifestyle relationships. Grade-to-grade relationships are the strongest, while parent education and alcohol-use patterns also show meaningful associations.

Python Chart-by-Chart Interpretation

The Python assets include five charts: Pearson correlation matrix, Pearson p-value heatmap, correlations with G3, strongest pair scatterplot and outlier context. These charts explain the relationship structure visually and support the Excel workbook values.

Python Chart 1: Pearson Correlation Matrix

Python Pearson correlation matrix heatmap
Python heatmap showing Pearson r values among the 16 selected numeric variables.

The Pearson correlation matrix heatmap shows all pairwise linear associations in one chart. The strongest positive block appears among G1, G2 and G3. This means the grade variables move together strongly across students.

The matrix also shows positive associations such as Medu–Fedu and Dalc–Walc. Medu–Fedu means mother education and father education are strongly related. Dalc–Walc means weekday and weekend alcohol consumption move together.

Negative cells show inverse linear relationships. The most important negative pattern for final grade is failures–G3, with r = -0.393316. Students with more past failures tend to have lower final grades.

Python Chart 2: Pearson p-value Heatmap

Python Pearson p-value heatmap
Python p-value heatmap showing two-tailed significance context for Pearson correlations.

The p-value heatmap shows which correlations are statistically significant. Strong grade relationships have extremely small p-values. Many weaker relationships also become statistically significant because the sample size is large.

This chart should always be interpreted together with the coefficient matrix. The p-value tells whether the result is statistically detectable. The Pearson r value tells the strength and direction of the linear relationship. A small p-value does not automatically mean a strong correlation.

For example, some G3 correlations such as goout or absences may be statistically significant but practically small. The correct report should include both r and p-value.

Python Chart 3: Correlations with G3

Python chart showing correlations with G3 final grade
Python chart ranking Pearson correlations between selected variables and G3 final grade.

This chart focuses on the main outcome variable, G3. It shows that G2 has the strongest positive relationship with G3, followed by G1. These two grade variables dominate the G3 correlation pattern.

The strongest negative relationship with G3 is failures. This makes sense educationally because students with more past failures tend to have lower final grades.

Other variables, such as studytime, Medu, Fedu, Dalc and Walc, have weaker relationships with G3. They may be statistically meaningful, but they are much smaller than the grade-to-grade relationships.

Python Chart 4: Strongest Pair Scatterplot

Python scatterplot for strongest Pearson correlation pair G2 and G3
Python scatterplot showing the strongest pair, G2 and G3.

The strongest pair scatterplot shows the relationship between G2 and G3. The points form a tight upward pattern. This visual pattern matches the Pearson correlation coefficient r = 0.918548.

This chart is the best visual explanation of the main result. It shows that students with higher second-period grades usually have higher final grades. The cloud is not perfectly straight, but it is strongly linear and positive.

When reporting this chart, avoid causal wording. Do not say that G2 causes G3. A better statement is that G2 and G3 have a very strong positive linear association.

Python Chart 5: Outlier Context

Python outlier context chart for Pearson correlation
Python chart showing outlier context for Pearson correlation interpretation.

The outlier context chart is important because Pearson correlation can be sensitive to influential observations. Extreme points can inflate, weaken or reverse a correlation depending on where they appear in the scatterplot.

The workbook flags several variables for review, including failures, absences, G1, G2 and G3. This does not mean Pearson correlation is invalid. It means the results should be interpreted with scatterplots and diagnostics, not only with numeric r values.

For the strongest G2–G3 relationship, the correlation remains very high, but the outlier chart still supports responsible reporting. For variables such as absences and failures, outlier context is even more important because these distributions are skewed.

R Chart-by-Chart Interpretation

The R assets validate the same analysis with colorful charts. The R report includes a Pearson correlation matrix, correlations with G3, strongest pair scatterplot and outlier context chart.

R Chart 1: Colorful Pearson Correlation Matrix

R colorful Pearson correlation matrix heatmap
R heatmap showing the pairwise Pearson correlation matrix.

The R correlation matrix confirms the same overall structure as the Python heatmap. The grade variables form the strongest positive cluster. Medu and Fedu also show a strong positive relationship, and Dalc and Walc show a strong positive lifestyle relationship.

This chart is useful because it validates the matrix pattern in a second software environment. When Python, R and Excel show the same relationship structure, the result is more trustworthy for readers.

R Chart 2: Colorful Correlations with G3

R colorful chart showing correlations with G3
R chart ranking variable correlations with G3 final grade.

The R G3 chart confirms that G2 and G1 are the strongest positive correlates of final grade. Failures is the strongest negative correlate. Studytime, parent education and alcohol-use variables have weaker but interpretable relationships.

This chart is ideal for students writing a report because it narrows the full matrix down to the final-grade outcome. It shows which predictors or background variables are most associated with G3.

R Chart 3: Colorful Strongest Pair Scatterplot

R colorful strongest pair scatterplot for G2 and G3
R scatterplot for the strongest Pearson correlation pair, G2 and G3.

The R scatterplot again shows the tight upward relationship between G2 and G3. The pattern supports the very strong positive Pearson coefficient.

Scatterplots are essential for Pearson correlation because they show whether the relationship is approximately linear. A high r should be supported by a line-like cloud, and the G2–G3 chart provides that visual support.

R Chart 4: Colorful Outlier Context

R colorful outlier context chart for Pearson correlation
R outlier context chart for Pearson correlation diagnostics.

The R outlier context chart reinforces the same assumption check as the Python chart. Some variables contain skewness or possible influential values. This is expected in real educational data.

The correct conclusion is not to reject Pearson correlation automatically. The correct conclusion is to combine Pearson r with visual checks. If a relationship is driven by a small number of extreme observations, Spearman correlation, robust correlation or a regression diagnostic check may be useful.

SPSS Output and Workflow Interpretation

The SPSS output PDF is included in the resources. SPSS is commonly used for Pearson correlation because it produces a clean correlation table with coefficients, significance values and sample sizes.

Open the SPSS Pearson Correlation Output PDF

In SPSS, Pearson correlation is usually run through Analyze → Correlate → Bivariate. Select the numeric variables, choose Pearson, select two-tailed significance, and request means and standard deviations if needed.

SPSS StepActionPurpose
1Open the dataset in SPSSEnsure variables such as G1, G2 and G3 are numeric.
2Go to Analyze → Correlate → BivariateOpen the bivariate correlation dialog.
3Move selected variables into the Variables boxInclude all numeric variables for the matrix.
4Select PearsonRequests Pearson product-moment correlation.
5Select two-tailed significanceTests whether r differs from zero.
6Interpret coefficient, Sig. and NReport r, p-value and sample size.

For the strongest pair, SPSS should be interpreted as: G2 and G3 have a very strong positive Pearson correlation, r ≈ .919, p < .001, N = 649. When reporting SPSS output, always include whether the test is two-tailed and whether missing values were handled pairwise or listwise.

Excel Worked File Explanation

The Excel workbook is a fully worked Pearson Correlation analysis file. It contains raw data, selected variables, descriptive statistics, a Pearson correlation matrix, pairwise N, p-value matrix, confidence interval sheets, pairwise results, assumptions, formulas and a dashboard.

Download the Pearson Correlation Full Excel Analysis File

Excel SheetPurposeWhat It Teaches
READMEExplains workbook structure and use.Shows dataset rows, numeric variables and sheet purpose.
DataStores the original uploaded dataset.Makes the analysis self-contained.
VariablesLists selected numeric variables.Shows which variables enter the Pearson matrix.
Descriptive_StatsSummarizes variables and diagnostics.Shows N, missing, mean, SD, skewness, kurtosis and outlier counts.
Pearson_MatrixFormula-based Pearson r matrix.Uses Excel CORREL for all variable pairs.
Pairwise_NCounts paired numeric observations.Checks sample size for each pair.
P_ValuesStores two-tailed p-values.Uses t statistics and T.DIST.2T logic.
CI95_LowerLower confidence interval matrix.Uses Fisher z transformation.
CI95_UpperUpper confidence interval matrix.Uses Fisher z transformation.
Pairwise_ResultsOne row per variable pair.Provides r, r², t statistic, df, p-value, CI, decision and interpretation.
AssumptionsAssumption checklist.Reviews numeric scale, linearity, outliers, normality and independence.
Formulas_MethodFormula documentation.Explains CORREL, p-value, CI and r² formulas.
DashboardSummary and chart-ready values.Highlights G3 correlations and strongest pair.

Excel Formula Method

The workbook uses the following Excel formula logic:

ItemExcel Formula / MethodPurpose
Pearson r=CORREL(x_range,y_range)Computes Pearson product-moment correlation coefficient.
Pairwise N=SUMPRODUCT(--ISNUMBER(x_range),--ISNUMBER(y_range))Counts valid paired numeric observations.
t statistic=r*SQRT((n-2)/(1-r^2))Test statistic for H0: r = 0.
Degrees of freedom=n-2Degrees of freedom for Pearson correlation test.
Two-tailed p-value=T.DIST.2T(ABS(t),df)Two-tailed significance value.
Fisher lower CI=TANH(ATANH(r)-NORM.S.INV(0.975)/SQRT(n-3))Lower 95% confidence limit for r.
Fisher upper CI=TANH(ATANH(r)+NORM.S.INV(0.975)/SQRT(n-3))Upper 95% confidence limit for r.
Effect size=r^2Shared variance between the two variables.

The Excel dashboard is especially useful because it provides the final story quickly: 649 dataset rows, 16 numeric variables, 120 variable pairs, main outcome G3, strongest pair G2–G3 and the interpretation rule for coefficient strength.

Python, R, SPSS and Excel Workflows

Pearson Correlation can be calculated in all four tools. The same statistical result should appear if the same variables, missing-value rules and numeric coding are used.

SoftwareMain WorkflowBest Use
PythonUse pandas for data preparation, scipy for Pearson r and p-values, and matplotlib for heatmaps and scatterplots.Automated charts, reproducible analysis and blog asset generation.
RUse cor(), cor.test(), pairwise loops and visualization tools for correlation matrices and scatterplots.Statistical validation and colorful publication-style graphics.
SPSSUse Analyze → Correlate → Bivariate, select Pearson, and request two-tailed significance.Formal output table for research reports and student assignments.
ExcelUse CORREL, SUMPRODUCT, T.DIST.2T, Fisher z formulas and dashboard sheets.Formula teaching, transparent workbook verification and manual reporting.

For a complete Salar Cafe workflow, use Excel to verify the formulas, Python to generate the main blog charts, R to validate the outputs, and SPSS to provide the official-style statistical output PDF.

Code Blocks and Excel Formulas

Python Code for Pearson Correlation

import pandas as pd
from scipy import stats

df = pd.read_csv("dataset.csv")

x_var = "G2"
y_var = "G3"

work = df[[x_var, y_var]].dropna().copy()
work[x_var] = pd.to_numeric(work[x_var], errors="coerce")
work[y_var] = pd.to_numeric(work[y_var], errors="coerce")
work = work.dropna()

r, p_value = stats.pearsonr(work[x_var], work[y_var])
n = len(work)
dfree = n - 2
t_value = r * ((dfree / (1 - r**2)) ** 0.5)

print("Variable X:", x_var)
print("Variable Y:", y_var)
print("N:", n)
print("Pearson r:", r)
print("R squared:", r**2)
print("t statistic:", t_value)
print("df:", dfree)
print("p-value:", p_value)

Python Code for Pearson Correlation Matrix

import pandas as pd
from scipy import stats

df = pd.read_csv("dataset.csv")

vars_used = [
    "age", "Medu", "Fedu", "traveltime", "studytime", "failures",
    "famrel", "freetime", "goout", "Dalc", "Walc", "health",
    "absences", "G1", "G2", "G3"
]

data = df[vars_used].apply(pd.to_numeric, errors="coerce")

corr_matrix = data.corr(method="pearson")

p_matrix = pd.DataFrame(index=vars_used, columns=vars_used, dtype=float)
n_matrix = pd.DataFrame(index=vars_used, columns=vars_used, dtype=float)

for x in vars_used:
    for y in vars_used:
        pair = data[[x, y]].dropna()
        n_matrix.loc[x, y] = len(pair)
        if x == y:
            p_matrix.loc[x, y] = None
        else:
            r, p = stats.pearsonr(pair[x], pair[y])
            p_matrix.loc[x, y] = p

print(corr_matrix)
print(p_matrix)

R Code for Pearson Correlation

df <- read.csv("dataset.csv", stringsAsFactors = FALSE)

x_var <- "G2"
y_var <- "G3"

work <- na.omit(df[, c(x_var, y_var)])
work[[x_var]] <- as.numeric(work[[x_var]])
work[[y_var]] <- as.numeric(work[[y_var]])

test <- cor.test(work[[x_var]], work[[y_var]], method = "pearson")

print(test)

cat("N:", nrow(work), "\n")
cat("Pearson r:", unname(test$estimate), "\n")
cat("R squared:", unname(test$estimate)^2, "\n")
cat("p-value:", test$p.value, "\n")

R Code for Pearson Correlation Matrix

df <- read.csv("dataset.csv", stringsAsFactors = FALSE)

vars_used <- c(
  "age", "Medu", "Fedu", "traveltime", "studytime", "failures",
  "famrel", "freetime", "goout", "Dalc", "Walc", "health",
  "absences", "G1", "G2", "G3"
)

data <- df[vars_used]
data[] <- lapply(data, as.numeric)

corr_matrix <- cor(data, use = "pairwise.complete.obs", method = "pearson")

p_matrix <- matrix(NA, nrow = length(vars_used), ncol = length(vars_used))
rownames(p_matrix) <- vars_used
colnames(p_matrix) <- vars_used

for(i in seq_along(vars_used)){
  for(j in seq_along(vars_used)){
    if(i != j){
      pair <- na.omit(data[, c(vars_used[i], vars_used[j])])
      p_matrix[i, j] <- cor.test(pair[[1]], pair[[2]], method = "pearson")$p.value
    }
  }
}

print(corr_matrix)
print(p_matrix)

SPSS Syntax for Pearson Correlation

* Pearson Correlation in SPSS.
OUTPUT CLOSE ALL.
OUTPUT NEW NAME=Pearson_Correlation_Output.

DESCRIPTIVES VARIABLES=age Medu Fedu traveltime studytime failures famrel freetime goout Dalc Walc health absences G1 G2 G3
  /STATISTICS=MEAN STDDEV MIN MAX.

CORRELATIONS
  /VARIABLES=age Medu Fedu traveltime studytime failures famrel freetime goout Dalc Walc health absences G1 G2 G3
  /PRINT=TWOTAIL
  /MISSING=PAIRWISE.

GRAPH
  /SCATTERPLOT(BIVAR)=G2 WITH G3
  /TITLE='Strongest Pearson Correlation Pair: G2 with G3'.

OUTPUT EXPORT
  /CONTENTS EXPORT=VISIBLE
  /PDF DOCUMENTFILE='Pearson-Correlation-SPSS-Output.pdf'.

Excel Formula Patterns for Pearson Correlation

Assume:
X_range = G2 values
Y_range = G3 values

Pearson r:
=CORREL(X_range,Y_range)

R squared:
=r^2

Pairwise N:
=SUMPRODUCT(--ISNUMBER(X_range),--ISNUMBER(Y_range))

Degrees of freedom:
=N-2

t statistic:
=r*SQRT((N-2)/(1-r^2))

Two-tailed p-value:
=T.DIST.2T(ABS(t),N-2)

Fisher z:
=ATANH(r)

Standard error of z:
=1/SQRT(N-3)

95% CI lower:
=TANH(ATANH(r)-NORM.S.INV(0.975)/SQRT(N-3))

95% CI upper:
=TANH(ATANH(r)+NORM.S.INV(0.975)/SQRT(N-3))

Decision:
=IF(p_value<0.05,"Significant correlation","Not significant")

Pearson Correlation Assumptions

Pearson correlation is simple to calculate, but the interpretation depends on assumptions and data checks. The workbook includes an assumptions sheet covering numeric scale, linearity, outliers, approximate normality for inference and independence.

AssumptionWhat It MeansWorkbook CheckDecision Guide
Numeric scale variablesPearson correlation is for quantitative variables.Variables sheet lists numeric variables only.Use numeric variables for r; use Spearman or Kendall for ordinal-heavy variables.
Linear relationshipThe association should be approximately linear.Dashboard and scatterplots show selected relationships.If the pattern is curved, Pearson r may understate or misrepresent association.
No extreme influential outliersOutliers can strongly distort Pearson r.Descriptive_Stats uses IQR outlier counts.Review scatterplots and consider robust or rank methods if outliers dominate.
Approximate normality for inferenceBivariate normality is ideal for p-values and confidence intervals.Skewness and kurtosis are calculated.Use graphs and sample-size context; do not rely on one number alone.
Independence of observationsRows should represent independent students or observations.Design assumption.If rows are repeated or clustered, use a different model.

For this dataset, Pearson correlation is appropriate for grade-to-grade relationships, especially G2–G3 and G1–G3. For variables with strong skewness or ordinal categories, Pearson r should be interpreted alongside scatterplots and possibly compared with rank-based measures.

How to Report Pearson Correlation

A complete Pearson correlation report should include the variables, sample size, coefficient, confidence interval if available, p-value, direction, strength and practical interpretation. It should also mention that correlation does not prove causation.

APA-style strongest-pair report: A Pearson product-moment correlation was computed to examine the linear association between G2 and G3. The relationship was very strong and positive, r(647) = .919, p < .001, N = 649. This indicates that students with higher second-period grades tended to have higher final grades. The shared variance was approximately 84.37%.

G3-focused report: G3 was most strongly correlated with G2, r = .919, and G1, r = .826. The strongest negative correlation with G3 was failures, r = -.393. This suggests that prior grade performance is the dominant correlate of final grade, while past failures have a moderate negative association.

Assumption-aware wording: Pearson correlation measures linear association. Scatterplots and outlier checks should be reviewed before final interpretation, especially for skewed or count-like variables such as failures and absences.

Common Mistakes in Pearson Correlation Interpretation

MistakeWhy It Is a ProblemBetter Practice
Claiming correlation proves causationPearson r is an association measure, not a causal test.Use “associated with” instead of “causes.”
Reporting only p-valuep-value does not show strength or direction.Report r, p-value and interpretation.
Ignoring scatterplotsPearson r can hide nonlinear patterns or outliers.Always inspect scatterplots.
Using Pearson for ordinal-only data without cautionOrdinal spacing may not be equal.Consider Spearman or Kendall as comparison methods.
Ignoring outliersA few extreme values can distort r.Use outlier context charts and diagnostics.
Confusing r and r²r shows direction and strength; r² shows shared variance.Report both only when useful and explain the difference.
Calling a weak significant correlation strongLarge samples can make small r values significant.Use effect-size labels based on r magnitude.
Comparing correlations without contextDifferent variables can have different distributions and outlier patterns.Use charts and assumptions before ranking importance.

Downloads and Resources

External References

For additional learning, review documentation and textbooks on Pearson product-moment correlation, Fisher z confidence intervals, bivariate correlation testing, correlation matrices, scatterplot interpretation and outlier diagnostics.

FAQs About Pearson Correlation

What is Pearson Correlation?

Pearson Correlation measures the strength and direction of a linear relationship between two quantitative variables. It is reported as r, ranging from -1 to +1.

What was the strongest Pearson correlation in this guide?

The strongest pair was G2 and G3, with Pearson r = 0.918548. This is a very strong positive linear association.

What does r = 0.918548 mean?

It means G2 and G3 move together very strongly in a positive linear direction. Students with higher G2 scores tend to have higher G3 scores.

What is the difference between r and r squared?

r shows direction and strength of linear association. r squared shows the proportion of shared linear variance. For G2–G3, r² is about 0.8437, or 84.37%.

Which variable has the strongest negative correlation with G3?

Failures has the strongest negative correlation with G3, r = -0.393316. This means more failures are associated with lower final grades.

Can Pearson correlation prove causation?

No. Pearson correlation measures association only. It does not prove that one variable causes another.

Can Excel calculate Pearson correlation?

Yes. Excel can calculate Pearson correlation with CORREL. The uploaded workbook also uses formulas for p-values, confidence intervals, pairwise N and r squared.

Can SPSS calculate Pearson correlation?

Yes. In SPSS, use Analyze → Correlate → Bivariate, select Pearson, and choose two-tailed significance.

What should I report in APA style?

You can write: “A Pearson correlation showed a very strong positive relationship between G2 and G3, r(647) = .919, p < .001, N = 649.”

When should I avoid Pearson correlation?

Use caution when the relationship is nonlinear, variables are purely ordinal, observations are not independent, or extreme outliers dominate the result. In those cases, consider scatterplots, Spearman correlation, Kendall correlation or regression diagnostics.

Need help applying this to your own data?

Salar Cafe can help interpret output, clean datasets, review assumptions, build dashboards and explain statistical results ethically.

Need help interpreting your data analysis results?

Contact Salar Cafe
Engr. Muhammad Yar Saqib author profile photo

Engr. Muhammad Yar Saqib

Engr. Muhammad Yar Saqib is an electrical engineer educated at the University of Bradford, United Kingdom, a writer and poet, and an Assistant Education Officer in the School Education Department, Punjab, serving since July 2017. He writes practical guides on statistics, SPSS, data analysis, mathematics and educational technology, with an emphasis on transparent methods, reproducible calculations and ethical learning support.