我有以下函數從卡方分佈中抽取一些數據,並使用最大似然比較X的分佈與已知的卡方分佈。該過程被模擬nSims
次。 (我這些結果進行比較,從置換的測試結果,但代碼除外)。'優化'找不到函數調用中的變量
chi2c <- function(xdf=2, yObs=100, xObs=100, nSims=1000, nPerm=500, alpha=0.05){
simResults <- sapply(1:nSims, function(x){
# Draw variables
x <- rchisq(xObs, df=xdf)
# Other variables not relevant here
# [[snip]]
# Permutation test
# [[snip]]
# Calculate the statistics necessary for maximum likelihood
n <<- length(x)
sumlx <<- sum(log(x))
sumx <<- sum(x)
# Calculate the maximum likelihood estimate
dfhat <- optimize(f=c2ll, interval=c(1, 10), maximum=TRUE)$maximum
# Calculate the test statistic: -2 times the log likelihood ratio
llr <- -2 * (c2ll(2) - c2ll(dfhat))
# Compare the test statistic to its asymptotic dist: chi-squared
lReject <- llr > qchisq(1 - alpha, df=1)
# Provide the results
# [[snip]]
})
# Calcuate means across simulations
rowMeans(simResults)
}
這個函數調用c2ll
,卡方似然函數
c2ll <- function(dfHat){
-n * log(gamma(dfHat/2)) - n * (dfHat/2) * log(2) +
(dfHat/2 - 1) * sumlx - sumx/2
}
此功能不只是我希望和準確,但我不明白爲什麼我必須設置全局最大似然統計(n
,sumlx
和sumx
)才能使其運行; optimize
找不到它們,如果我只使用<-
將它們設置在函數內部。我嘗試將它們設置在optimize
之內,但那也不起作用。謝謝你的幫助。
Charlie
我有點困惑。它看起來像人們所期望的那樣行事:如果c2ll是全局定義的,那麼詞法範圍會要求任何變量查找首先在c2ll中發生,然後在全局中發生。如果將c2ll的所有輸入定義爲函數參數,那麼混淆會更少。 – 2010-11-17 07:54:36