対数尤度比に基づく独立性の検定 Last modified: Aug 19, 2009
目的
対数尤度比に基づく独立性の検定を行う。
この関数は htest クラス・オブジェクトを返すので,結果は print.htest により表示される。
使用法
G2(mat, correct=FALSE)
引数
mat 分割表
correct Williams の連続性の補正を行うときに TRUE とする
省略されたときには,連続性の補正は行わない
ソース
インストールは,以下の 1 行をコピーし,R コンソールにペーストする
source("http://aoki2.si.gunma-u.ac.jp/R/src/G2.R", encoding="euc-jp")
# 対数尤度比に基づく独立性の検定を行う(htest クラスの結果を返す)
G2 <- function( mat, # 分割表(合計欄を除く)
correct=FALSE) # Williams の連続性の補正を行うときに TRUE にする
{
ln <- function(n) sum(ifelse(n == 0, 0, n*log(n))) # n*ln(n) を適切に行う関数
data.name <- deparse(substitute(mat))
method <- "対数尤度比に基づく独立性の検定(G-squared test)"
n <- sum(mat) # 全サンプルサイズ
n1 <- rowSums(mat) # 行和
n2 <- colSums(mat) # 列和
G2 <- 2*(ln(mat)-ln(n1)-ln(n2)+ln(n)) # G 統計量
a <- nrow(mat) # 分割表の行数
b <- ncol(mat) # 分割表の列数
df <- (a-1)*(b-1) # G の自由度
if (correct == TRUE) { # 連続性の補正
method <- paste(method, "連続性の補正")
G2 <- G2/(1+(n*sum(1/n1)-1)*(n*sum(1/n2)-1)/(6*n*a*b))
}
P <- pchisq(G2, df, lower.tail=FALSE) # P 値
names(G2) <- "G-squared"
names(df) <- "df"
return(structure(list(statistic=G2, parameter=df,
p.value=P, method=method, data.name=data.name, observed=mat),
class="htest")) # 結果をまとめて返す
}
G2(matrix(c(5, 5, 1, 6, 4, 4, 2, 2, 1), byrow=TRUE, nc=3))
G2(matrix(c(4, 5, 2, 0, 0, 7, 6, 1, 1, 0, 3, 1), byrow=TRUE, nc=4))
G2(matrix(c(4, 5, 2, 0, 0, 7, 6, 1, 1, 0, 3, 1), byrow=TRUE, nc=4), correct=TRUE)
使用例
> G2(matrix(c(5, 5, 1, 6, 4, 4, 2, 2, 1), byrow=TRUE, nc=3))
対数尤度比に基づく独立性の検定(G-squared test)
data: matrix(c(5, 5, 1, 6, 4, 4, 2, 2, 1), byrow = TRUE, nc = 3)
G-squared = 1.8024, df = 4, p-value = 0.772
> G2(matrix(c(4, 5, 2, 0, 0, 7, 6, 1, 1, 0, 3, 1), byrow=TRUE, nc=4))
対数尤度比に基づく独立性の検定(G-squared test)
data: matrix(c(4, 5, 2, 0, 0, 7, 6, 1, 1, 0, 3, 1), byrow = TRUE, nc = 4)
G-squared = 15.3646, df = 6, p-value = 0.0176
> G2(matrix(c(4, 5, 2, 0, 0, 7, 6, 1, 1, 0, 3, 1), byrow=TRUE, nc=4), correct=TRUE) # 連続性の補正を行うとき
対数尤度比に基づく独立性の検定(G-squared test) 連続性の補正
data: matrix(c(4, 5, 2, 0, 0, 7, 6, 1, 1, 0, 3, 1), byrow = TRUE, nc = 4)
G-squared = 13.7765, df = 6, p-value = 0.0322
直前のページへ戻る
E-mail to Shigenobu AOKI