I'm building the pdf of a random variable and, in order to do so, I need to compute the integral of a function. The pdf looks like the following where I have intentionally separated the exponentials so to make it easier to read and distinguish the parts that depend from the x
under integration.
The values of alpha, beta and miu
are know and the summations are done on the values of t_k
which are also given and known as
I have read countless posts, ppt presentations, etc about how to use vectorize in R but I have to admit that I still don't understand what's going on there.
I thought I had fixed the problem in my code but when I run it using the dataset available here (https://onedrive.live.com/redir?resid=BBBAA03E98D384C6!3542&authkey=!AF8x7Wudm0LTubc&ithint=file%2ccsv)
test<-probability.function(c(0.1, 5, 19), test.times, 30, 0.1)
it returns warning messages telling me that
Warning messages:
1: In values[i] <- integrate(Vectorize(integrand, vectorize.args = "x"), ... :
number of items to replace is not a multiple of replacement length$
which makes me believe that I still haven't vectorized my function properly. Any suggestions on what I'm doing wrong? Also, where can I find a clear explanation (possibly with several examples) of why we need to vectorize a function in order to run integrate? I would really appreciate!
## Pdf function for the random variable (1-D)
probability.function=function(paramss, event.times, length.interval, granularity.interval) {
tt<-sort(event.times)
li<-length.interval
gi<-granularity.interval
s<-seq(tail(tt,1), tail(tt,1)+li, by=gi) #seed.times on which I compute the value of the pdF (starting point is the last occurence time)
parr1<-paramss[1]
parr2<-paramss[2]
parr3<-paramss[3]
integrand <- function(x, top, params, data, seed.time) {
t<-sort(data)
par1<-params[1]
par2<-params[2]
par3<-params[3]
top<-top
s<-seed.time
value <- (par1 + sum(par2*exp(-par3*(x - t)))) *
(par1 + sum(par2*exp(-par3*(top - t))) + par2*exp(-par3*(top - x))) *
exp(-par1*(x-tail(t,1))) *
exp(-par2/par3*sum(exp(-par3*(tail(t,1)-t)) - exp(-par3*(top-t)))) *
exp(-par2/par3*(1-exp(-par3*(top-x))))
return(value)
}
values<- rep(0,length(s))
for(i in 1:length(values)) {
values[i] <- integrate(Vectorize(integrand, vectorize.args='x'), lower=tail(tt,1), upper=s [i], top=s[i], params=c(parr1, parr2, parr3), data=tt, seed.time=s[i])
}
return(values)
}