chisplot <- function(x) { if (!is.matrix(x)) stop("x is not a matrix") ### determine dimensions n <- nrow(x) p <- ncol(x) # xbar <- apply(x, 2, mean) S <- var(x) S <- solve(S) index <- (1:n)/(n+1) # xcent <- t(t(x) - xbar) di <- apply(xcent, 1, function(x,S) x %*% S %*% x,S) # quant <- qchisq(index,p) plot(quant, sort(di), ylab = "Ordered distances", xlab = "Chi-square quantile", lwd=2,pch=1) } bivden<-function(x, y, ngridx = 30, ngridy = 30, constant.x = 1, constant.y = 1) { #x and y are vectors containing the bivariate data #ngridx and ngridy are the number of points in the grid # mx <- mean(x) sdx <- sqrt(var(x)) my <- mean(y) sdy <- sqrt(var(y)) #scale x and y before estimation x <- scale(x) y <- scale(y) # den <- matrix(0, ngridx, ngridy) # #find possible value for bandwidth # n <- length(x) # hx <- constant.x * n^(-0.2) hy <- constant.y * n^(-0.2) h <- hx * hy hsqrt <- sqrt(h) # seqx <- seq(range(x)[1], range(x)[2], length = ngridx) seqy <- seq(range(y)[1], range(y)[2], length = ngridy) # for(i in 1:n) { X <- x[i] Y <- y[i] xx <- (seqx - X)/hsqrt yy <- (seqy - Y)/hsqrt den <- den + outer(xx, yy, function(x, y) exp(-0.5 * (x^2 + y^2))) } den <- den/(n * 2 * pi * h) seqx <- sdx * seqx + mx seqy <- sdy * seqy + my result <- list(seqx = seqx, seqy = seqy, den = den) result } chiplot<-function(x,y,vlabs=c("X","Y"),matrix="NO") { n<-length(x) ind<-numeric(length=n) for(i in 1:n) { for(j in (1:n)[-i]) if(x[i]>x[j]&y[i]>y[j]) ind[i]<-ind[i]+1 } ind<-ind/(n-1) # ind1<-numeric(length=n) for(i in 1:n) { for(j in (1:n)[-i]) if(x[i]>x[j]) ind1[i]<-ind1[i]+1 } ind1<-ind1/(n-1) # ind2<-numeric(length=n) for(i in 1:n) { for(j in (1:n)[-i]) if(y[i]>y[j]) ind2[i]<-ind2[i]+1 } ind2<-ind2/(n-1) # s<-sign((ind1-0.5)*(ind2-0.5)) # chi<-(ind-ind1*ind2)/sqrt(ind1*(1-ind1)*ind2*(1-ind2)) # lambda<-4*s*pmax((ind1-0.5)^2,(ind2-0.5)^2) thresh<-4*(1/(n-1)-0.5)^2 # # if(matrix=="NO") { par(mfrow=c(1,2)) plot(x,y,xlab=vlabs[1],ylab=vlabs[2]) plot(lambda[abs(lambda)=const2]<-0 l<-length(w[w==0]) if(l<0.5*n) break else const2<-2*const2 } tx<-sum(w*x)/sum(w) sx<-sqrt(sum(w*(x-tx)^2)/sum(w)) ty<-sum(w*y)/sum(w) sy<-sqrt(sum(w*(y-ty)^2)/sum(w)) r<-sum(w*(x-tx)*(y-ty))/(sx*sy*sum(w)) const2<-c2 wold<-w for(i in 1:100) { z1<-((y-ty)/sy+(x-tx)/sx)/sqrt(2*(1+r)) z2<-((y-ty)/sy-(x-tx)/sx)/sqrt(2*(1+r)) esq<-z1*z1+z2*z2 for(j in 1:10) { w[esq=const2]<-0 l<-length(w[w==0]) if(l<0.5*n) break else const2<-2*const2 } tx<-sum(w*x)/sum(w) sx<-sqrt(sum(w*(x-tx)^2)/sum(w)) ty<-sum(w*y)/sum(w) sy<-sqrt(sum(w*(y-ty)^2)/sum(w)) r<-sum(w*(x-tx)*(y-ty))/(sx*sy*sum(w)) term<-sum((w-wold)^2)/(sum(w)/n)^2 if(term<-err) break else {wold<-w const2<-c2 } } param<-c(tx,ty,sx,sy,r) param }