Reputation: 347
I have the following R code:
The first part is working:
denSim <- function(n,nrow,ncol,v,ar) {
XX <- matrix(NA,nrow=nrow,ncol=ncol)
h1 <- h2 <- kknum <- kksum <- abc <- NULL
for(i in 1:n){
XX[,i] <- arima.sim(list(order=v,ar=ar), n=nrow)
h1[i]<-length(XX[,i])^(-1/5)
h2[i]<-sd(XX[,i])*h1[i]
kknum[[i]] <- exp(-0.5*((XX[nrow,i]-XX[,i])/bw.nrd0(XX[,i]))^2)
kksum[i]<-sum(kknum[[i]][-nrow])
abc[i]<- 1/(h2[i]*sqrt(2*pi))
}
Simls <- list(XX = XX,h1 = h1,h2=h2,kknum = kknum,kksum = kksum,abc = abc)
return(Simls)
}
Sim <- denSim(n=200,nrow=500,ncol=200,v=c(1,0,0),ar=0.6)
The second part is not working:
pdf <- function(z,i){
ABC <-Sim$abc[i]
Z <- z - Sim$XX[-1,i]
H2 <- Sim$h2[i]
eta <- ((Z)/H2)^2
KKN <- Sim$kknum[[i]][-500]
KKS <- Sim$kksum[i]
return(ABC*sum(KKN*exp(-0.5*eta))/KKS)
}
cdf <- function(i) integrate(pdf,0.6*mean(Sim$XX[,i]),20,i)$value
cdf(1)
what is the problem?
Upvotes: 0
Views: 76
Reputation: 59385
integrate(...)
takes a "vectorized function", e.g. a function which takes a vector as argument and returns a vector of the same length. Your function pdf(...)
takes a scalar value for x
and returns a scalar.
Fortunately there is a simple solution, the Vectorize(...)
function in R is a wrapper that turns a scalar function into a vector function.
pdf.vect <- Vectorize(pdf)
cdf <- function(i) integrate(pdf.vect,0.6*mean(Sim$XX[,i]),20,i)$value
cdf(1)
# [1] 0.6820746
EDIT (Response to OP's comment)
Yes, but integrate(...)
is also not vectorized, so you have to do that as well.
cdf <- Vectorize(function(x,i) integrate(pdf.vect,0.6*mean(Sim$XX[,i]),x,i)$value)
x <- seq(0,5,0.1)
plot(x,pdf.vect(x,1),type="l", ylab="Y")
par(new=T)
plot(x,cdf(x,1),yaxt="n", xaxt="n", col="red",type="l",ylab="",)
Upvotes: 2