讓我們嘗試一些更具有統計學或數學明智的,如非標準化正態分佈,即表達式:exp(-x^2)
您正試圖創建一個新的表達式(實際上是一個R「調用」),它將被解析爲該表達式的乘積exp( X * t)的,所以你需要a)提供一個真正的R語言對象的功能和b)使用不會破壞它的函數來處理它。 quote
函數將構造一個表達式,substitute
可以在「語言級別」上操作。不幸的是,function
函數會以不符合您的符號意圖的方式評估「body」參數,因此您需要使用body<-
(函數),該函數在賦值運算符的右側使用表達式。我會在一些print(.)
調用我曾經明白的地方,我在我早期的努力走錯了調試的離開:
logmgf <- function(integrand, upper, lower, t) {
expr <- substitute(integrand *exp(x*t), list(integrand=integrand))
print(expr)
func <- function(x){} # builds an empty function in x
body(func)<- expr # could have also set an environment
# but in this case using envir=parent.frame() is not appropriate
print(func)
integral <- integrate(func, upper=upper,
# notice need to name the parameters
lower=lower
# else they would be positionally matched
# (and therefore reversed in this case)
)$value
# the integrate fn returns a loist and the numeric part is in $value
logmgf <- log(integral)
}
res <- logmgf(quote(exp(-x^2)), upper = Inf, lower = -Inf, t = 0)
> res
[1] 0.5723649
MGF的是從-Inf集成到INF(或受限域功能只在x的定義值上)。
我想檢查我會從已知的參數得到正確的答案,所以我說回正確的標準化常數正態分佈:
mgf <- function(integrand, upper, lower, t) {
expr <- substitute(integrand *exp(x*t), list(integrand=integrand))
func <- function(x){}; body(func)<- expr
integral <- integrate(func, upper=upper, lower=lower)$value
}
res <- mgf(quote((1/sqrt(2*pi))*exp(-x^2/2)), upper = Inf, lower = -Inf, t = 0)
res
#[1] 1
@xionglui:我考慮張貼問題,然後將其刪除立即得到一個響應答案作爲破壞StackOverflow。 – 2015-03-02 21:29:44