Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206531

How to make sure R Integrate function skips a value where the function is undefined?

$
0
0

I have a function f which is defined with the help of function g. I am trying to calculate its entropy h_f. The error I get is the integral is probably divergent. My R code is the following:

phi <- function(x, m, s) (1/sqrt(2*pi*s^{2}))*exp((-1/2*s^{2})*(x-m)^{2})
g <- function(x, p) p*phi(x, -1, 0.2)+(1-p)*phi(x, -0.5, 1) 
f <- function(x, p) (1/x^{2})*g(log(x),p)
f1 <- function(x,p) (f(x,p)*(log(g(log(x),p))-2*log(x))) ##This is basically f(x)*log(f(x)) 

h_f <- function(p) -(integrate(f1, lower=0, upper=Inf, p=p)$value)
h_f <- Vectorize(h_f)

p <- seq(0,1, 0.01)
h_f(p)

Things I have tried: I tried setting res.tol to a different number, which changed the error into number of subdivisions has exceeded. Then I realized that the whole error persists perhaps because the definition of f depends on the division by x^{2}, I tried to substitute the lower limit of x with 1e-5 which works well and gives me finite values for p in [0,1]. However I am trying to figure out how to get the integrate function to give out NAs if x==0. I tried different versions of:

 h_f <- function(p){
              if(x==0) NA
              else{
                  -(integrate(f1, lower=0, upper=Inf, p=p)$value)
                   }
                  }

But of course that doesn't work, because x is not found in the framework of h_f. I have tried different workarounds but I don't seem to get it right. It's possible I am missing something obvious, would be grateful for any help.


Viewing all articles
Browse latest Browse all 206531

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>