setwd("C:/Users/Daniel Westhoff/Documents/Lehre/Angewandte Stochastik II/Übungsblätter/Blatt3") #1) empiricalDistr = function(x, path){ x=sort(x) n=length(x) y=c(1:n) for(i in 1:length(x)){ y[i] = length(x[x<=x[i]])/n } png(filename=paste(path, ".png", sep=""), width=800, height=800, res=180) plot(x,y,lwd=2, type="l", main="ECDF" ,xlab="x", ylab="F(x)") dev.off() } x=rnorm(1000,0,1) empiricalDistr(x, "test") #2) #a) epanechnikov=function(x){ if(x>1 | x<(-1)){ return(0) } return(0.75*(1-x^2)) } estDensity=function(t,x,h){ sum=0 for(i in 1:length(x)){ sum=sum+epanechnikov((t-x[i])/h) } return(1/(length(x)*h)*sum) } #b) x=rnorm(200,0,1) col=1:8 count=1 values=c(0.1, 0.2,0.5,1,2,4,5) int=seq(-4,4,0.1) for(h in values){ res=c() for(i in 1:length(int)){ res=c(res, estDensity(int[i], x, h)) } if(h==0.1){ plot(int, res, type="l", col=col[count], lwd=2) }else{ lines(int, res, type="l", col=col[count], lwd=2) } count=count+1 } lines(int, dnorm(int, 0,1), col=8, lwd=2) legend("topleft", legend=c(values, "N(0,1)"), fill=col) #c) h_opt=function(x,values){ n=length(x) hopt=0 prodopt=0 for(h in values){ prod=1 for(i in 1:n){ y=c(x[1:(i-1)], x[(i+1):n]) if(i==1){ y=x[2:n] } if(i==n){ y=x[1:(n-1)] } prod=prod*estDensity(x[i],y,h) } if(prod>prodopt){ hopt=h prodopt=prod } } return(hopt) } #d) values=seq(0.7,2,0.05) hopt=h_opt(x,values) print(hopt) int=seq(-4,4,0.1) res=c() for(i in 1:length(int)){ res=c(res, estDensity(int[i], x, hopt)) } plot(int, res, type="l", lwd=2) lines(int, dnorm(int), col="red", lwd=2)