[R] Integration with an Indicator Function in R
Uwe Ligges
ligges at statistik.tu-dortmund.de
Sat Feb 19 18:14:00 CET 2011
On 17.02.2011 22:10, li li wrote:
> Hi all,
> I have some some problem with regard to finding the integral of a
> function containing an indicator function.
> please see the code below:
>
> func1<- function(x, mu){
> (mu^2)*dnorm(x, mean = mu, sd = 1)*dgamma(x, shape=2)}
> m1star<- function(x){
> integrate(func1, lower = 0, upper = Inf,x)$val}
> T<- function(x){
> 0.3*dnorm(x)/(0.3*dnorm(x)+0.7*m1star(x))}
>
> func2<- function(x,c){(T(x)<=c)*0.3*dnorm(x)}
> func3<- function(x,c){(T(x)<= c)*(0.3*dnorm(x)+0.7*m1star(x))}
> numer<- function(c){
> integrate(func2, -Inf, Inf, c)$val}
>
> denom<- function(c){
> integrate(func3, lower, Inf,c)$val}
>
>
>
> The error message is as below :
>
>> numer(0.5)
> Error in integrate(func1, lower = 0, upper = Inf, x) :
> the integral is probably divergent
Several problems:
1. Your m1star does not work vectorized which is required here.
This can be fixed by changing the function as follows:
m1star <- function(x){
sapply(x, function(x) integrate(func1, lower = 0, upper = Inf, x =
x)$val)
}
2. You will find that func2 calculates T(x). Note that T(x) is not
undefined for x=0.
I have not investigated further, but my guess is that your problem needs
some rethinking ...
Best,
Uwe Ligges
>
>
> Thank you very much!
> Hannah
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list