Calculate the Phi coefficient (Matthews correlation coefficient for 2x2) between two binary variables. The Phi coefficient measures the association between two binary variables and ranges from -1 to 1.
def phi_coefficient(x: list[int], y: list[int]) -> float:
n11 = sum(1 for a, b in zip(x, y) if a == 1 and b == 1)
n10 = sum(1 for a, b in zip(x, y) if a == 1 and b == 0)
n01 = sum(1 for a, b in zip(x, y) if a == 0 and b == 1)
n00 = sum(1 for a, b in zip(x, y) if a == 0 and b == 0)
numerator = (n11 * n00) - (n10 * n01)
denominator = ((n11 + n10) * (n11 + n01) * (n00 + n10) * (n00 + n01)) ** 0.5
if denominator == 0:
return 0.0
return round(numerator / denominator, 4)n11, n10, n01, n00.(n11 * n00) - (n10 * n01) captures the difference between concordant and discordant pairs.