Well, so it confused me for more than 3 days and, without taking another step closer to the solution, I am going to try my luck here.
In the past, I wrote some code for one sorted dataset in a specific one, and it looks like this:
n <- length(data) maxobs <- max(data) minobs <- min(data) FG <- function(m=NULL, h = NULL){ n<- length(data) #Number of observations if (m<minobs){FG = 0} else { if (m >maxobs){FG = 1} else { FG = sum(pnorm((m - data)/h)-pnorm((minobs-data)/h))/sum(pnorm((maxobs - data)/h)-pnorm((minobs-data)/h)) }} return(FG) } f<- function(m,h){ f<- FG(m,h)^n return(f) } ##Integration max <- NULL delta<- function(h,max=maxobs){ delta <- integrate(Vectorize(f), minobs, max, h)$value return (delta) }
which works PERFECTLY. For example, if you select the data: = c (1,2,3,4,5), you get the correct result for
> delta(0.1, maxobs) [1] 0.6300001
However, now I am trying to generalize it for each sorted data set, so what I did (it was clear: the data set x is sorted before all these functions are executed)
FG <- function(x, m=NULL, h = NULL){ n<- length(x) #Number of observations maxobs <- max(x) minobs <- min(x) if (m<minobs){FG = 0} else { if (m >maxobs){FG = 1} else { FG = sum(pnorm((m - x)/h)-pnorm((minobs-x)/h))/sum(pnorm((maxobs - x)/h)-pnorm((minobs-x)/h)) }} return(FG) } f<- function(x,m,h){ n <- length(x) f<- FG(x,m,h)^n return(f) } ##Integration delta<- function(x,h,maxu= max(x)){ minobs <- min(x) delta <- integrate(Vectorize(f), minobs, maxu, h)$value return (delta) }
But now delta(data,0.1)
gives
delta(data,0.1) [1] 0.
That makes no sense to me. Same function, same data set, but now with the wrong value. What am I doing wrong?
Any help would be greatly appreciated.
EDIT: After taking a closer look at the Vectorize function and integrating the function, I now edited the delta function:
delta<- function(x,h,maxu= max(x)){ minobs <- min(x) delta <- integrate(Vectorize(f, vectorize.args= c("m","h")), minobs, maxu, h)$value return (delta) }
but now it just leads to another error:
Integration error (Vectorize (f, vectorize.args = c ("m", "h")), lower = minobs: function evaluation gave the result of the wrong length
I thought Vectorize should have prevented such errors?