#--1
#--Cargamos libreria y datos
library(MASS)
data(geyser)
attach(geyser)
hist<-hist(waiting)
help(hist,freq=F)
hist(waiting,breaks=50,freq=F)
hist(waiting,breaks=100,freq=F)




#--2
#---- Función Naive
naive<-function(x,muestra,h){
    nx=length(x)
    fx=numeric(nx)
    for (i in 1:nx){
    fx[i]=mean((x[i]-h<muestra)&(muestra<x[i]+h))/(2*h)
    }
return(fx)
}


x<-seq(min(waiting),max(waiting),by=0.01)
h<-4
est_naive<-nucleo_uni(x,waiting,h)
windows()
plot(hist,freq=F)
lines(est_naive~x)


#--3
nucleo_uniforme<-function(x){
 apply(x,2,function(x){ifelse(abs(x)<1,1/2,0)})
}


nucleo_epa<-function(x){
    apply(x,2,function(x){ ifelse(abs(x)<1,3/4*(1-x^2),0)})
}

#est_nucleo<-function(x,h,muestra){
#    nx<-length(x)
#    sol=numeric(nx)
#    for(i in 1:nx){
#    sol[i]<-(1/nx*h)*sum(dunif((x[i]-muestra)/h,-1,1))
#    }
#    return(sol)
#}

est_nucleo<-function(x,h,muestra,nucleo){
    apply(nucleo(outer(x,muestra,"-")/h),1,"mean")*(1/h)
}


est_uni<-est_nucleo(x,h,waiting,nucleo_uniforme)
windows()
plot(hist,freq=F)
lines(est_uni~x)

est_epa<-est_nucleo(x,h,waiting,nucleo_epa)
windows()
plot(hist,freq=F)
lines(est_epa~x)
