我有以下函数从卡方分布中抽取一些数据,并使用最大似然比较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