-
Notifications
You must be signed in to change notification settings - Fork 0
/
prop_test.m
66 lines (58 loc) · 1.69 KB
/
prop_test.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
function [h,p, chi2stat,df] = prop_test(X , N, correct)
% [h,p, chi2stat,df] = prop_test(X , N, correct)
%
% A simple Chi-square test to compare two proportions
% It is a 2 sided test with alpha=0.05
%
% Input:
% X = vector with number of success for each sample (e.g. [20 22])
% N = vector of total counts for each sample (e.g. [48 29])
% correct = true/false : Yates continuity correction for small samples?
%
% Output:
% h = hypothesis (H1/H0)
% p = p value
% chi2stat= Chi-square value
% df = degrees of freedom (always equal to 1: 2 samples)
%
% Needs chi2cdf from the Statistics toolbox
% Inspired by prop.test() in "R" but much more basic
%
% Example: [h,p,chi]=prop_test([20 22],[48 29], true)
% The above example tests if 20/48 differs from 22/29 using Yate's correction
if ~exist('correct','var')
correct = 'false';
end
if (length(X)~= 2)||(length(X)~=length(N))
disp('Error: bad vector length')
elseif (X(1)>N(1))|| (X(2)>N(2))
disp('Error: bad counts (X>N)')
else
df=1; % 2 samples
% Observed data
n1 = X(1);
n2 = X(2);
N1 = N(1);
N2 = N(2);
% Pooled estimate of proportion
p0 = (n1+n2) / (N1+N2);
% Expected counts under H0 (null hypothesis)
n10 = N1 * p0;
n20 = N2 * p0;
observed = [n1 N1-n1 n2 N2-n2];
expected = [n10 N1-n10 n20 N2-n20];
if correct == false
% Standard Chi-square test
chi2stat = sum((observed-expected).^2 ./ expected);
p = 1 - chi2cdf(chi2stat,1);
else
% Yates continuity correction
chi2stat = sum((abs(observed - expected) - 0.5).^2 ./ expected);
p = 1 - chi2cdf(chi2stat,1);
end
h=0;
if p<0.05
h=1;
end
end
end