2015-03-02 20 views
2

所以我剛剛回答了一個問題,一旦它被回答(正確地我認爲),提問者刪除它。所以這裏又是:集成一個函數作爲參數在R


我是R新手,需要幫助讓這個函數工作。我需要創建一個函數,它可以爲任何函數找到mgf的日誌,併爲指定的t返回值。我做了大量的研究,並且發現了很多告訴我使用Vectorize()的東西,並且確保我正確定義了我的參數,但我似乎仍然無法使其工作。我會愛如果有人能幫助我!

我需要編寫返回MGF的自然對數

# I'm using the expression 2*x as an example 
# You can use any integrand as long as it is a function of x 
logmgf <- function(integrand, upper, lower, t) { 
    expression <- function(x, t) { 
    integrand * exp(x * t) 
    } 
    integrate <- integrate(expression(x, t), upper, lower) 
    logmgf <- log(Vectorize(integrate[1])) 
    return(logmgf) 
} 
logmgf(2 * x, upper = Inf, lower = 0, t = 0) 

問3小時前一個數值向量函數 熊呂

+0

@xionglui:我考慮張貼問題,然後將其刪除立即得到一個響應答案作爲破壞StackOverflow。 – 2015-03-02 21:29:44

回答

2

讓我們嘗試一些更具有統計學或數學明智的,如非標準化正態分佈,即表達式: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 
相關問題