Skip to content

Commit

Permalink
Merge pull request #237 from rikhuijzer/descriptives-t-test
Browse files Browse the repository at this point in the history
Add t-test for cases where only stats are known
  • Loading branch information
andreasnoack committed Jun 15, 2021
2 parents 81120d3 + 4be6509 commit dd35ae0
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/t.jl
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,25 @@ end
testname(::EqualVarianceTTest) = "Two sample t-test (equal variance)"
population_param_of_interest(x::TwoSampleTTest) = ("Mean difference", x.μ0, x.xbar) # parameter of interest: name, value under h0, point estimate

"""
EqualVarianceTTest(nx::Int, ny::Int, mx::Real, my::Real, vx::Real, vy::Real, μ0::Real=0)
Perform a two-sample t-test of the null hypothesis that samples `x` and `y` described by the number
of elements `nx` and `ny`, the mean `mx` and `my`, and variance `vx` and `vy` come from distributions
with equals means and variances. The alternative hypothesis is that the distributions have different
means but equal variances.
Implements: [`pvalue`](@ref), [`confint`](@ref)
"""
function EqualVarianceTTest(nx::Int, ny::Int, mx::Real, my::Real, vx::Real, vy::Real, μ0::Real=0)
xbar = mx - my
stddev = sqrt(((nx - 1) * vx + (ny - 1) * vy) / (nx + ny - 2))
stderr = stddev * sqrt(1/nx + 1/ny)
t = (xbar - μ0) / stderr
df = nx + ny - 2
EqualVarianceTTest(nx, ny, xbar, df, stderr, t, μ0)
end

"""
EqualVarianceTTest(x::AbstractVector{T<:Real}, y::AbstractVector{T<:Real})
Expand All @@ -146,12 +165,9 @@ Implements: [`pvalue`](@ref), [`confint`](@ref)
"""
function EqualVarianceTTest(x::AbstractVector{T}, y::AbstractVector{S}, μ0::Real=0) where {T<:Real,S<:Real}
nx, ny = length(x), length(y)
xbar = mean(x) - mean(y)
stddev = sqrt(((nx - 1) * var(x) + (ny - 1) * var(y)) / (nx + ny - 2))
stderr = stddev * sqrt(1/nx + 1/ny)
t = (xbar - μ0) / stderr
df = nx + ny - 2
EqualVarianceTTest(nx, ny, xbar, df, stderr, t, μ0)
mx, my = mean(x), mean(y)
vx, vy = var(x), var(y)
EqualVarianceTTest(nx, ny, mx, my, vx, vy, μ0)
end


Expand Down
13 changes: 13 additions & 0 deletions test/t.jl
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,25 @@ end
@test default_tail(tst) == :both
show(IOBuffer(), tst)

n1 = length(a1)
n2 = length(a2)
m1 = mean(a1)
m2 = mean(a2)
v1 = var(a1)
v2 = var(a2)

tst2 = EqualVarianceTTest(n1, n2, m1, m2, v1, v2)
@test tst.df == tst2.df
@test tst.t == tst2.t
@test pvalue(tst) == pvalue(tst2)

tst = UnequalVarianceTTest(a1, a2)
@test abs(tst.df - 7.03) <= 0.01
@test abs(tst.t - 1.959) <= 1e-3
@test abs(pvalue(tst) - 0.091) <= 1e-3
@test all(abs.([confint(tst)...] - [-0.0196, 0.2096]) .<= 1e-4)
@test default_tail(tst) == :both
show(IOBuffer(), tst)

end
end

0 comments on commit dd35ae0

Please sign in to comment.