Skip to content

Instantly share code, notes, and snippets.

@misshie
Created October 19, 2023 02:34
Show Gist options
  • Save misshie/58aebcf8bc56db8f32811b884885030f to your computer and use it in GitHub Desktop.
Save misshie/58aebcf8bc56db8f32811b884885030f to your computer and use it in GitHub Desktop.
2x2 table chi squared test ... use at your own risk ;)
require 'statistics2'
def chisq_test(a, b, c, d)
total = a + b + c + d
row1_total = a + b
row2_total = c + d
col1_total = a + c
col2_total = b + d
e_a = (row1_total * col1_total).to_f / total
e_b = (row1_total * col2_total).to_f / total
e_c = (row2_total * col1_total).to_f / total
e_d = (row2_total * col2_total).to_f / total
chisq =
((a - e_a)**2 / e_a) + ((b - e_b)**2 / e_b) + ((c - e_c)**2 / e_c) + ((d - e_d)**2 / e_d)
Statistics2.chi2_x(1, chisq)
end
pp chisq_test(0,2,3,4) # => 0.25683925795785645
pp chisq_test(1,2,3,4) # => 0.7781596861761657
pp chisq_test(10,20,30,40) # => 0.372998483613487
pp chisq_test(100,20,30,40) # => 7.044113736753843e-09
pp chisq_test(1000,20,30,40) # => 0.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment