"johansen"<-
function(x, L = 2)
{
#Johansen Test of cointegration for multivariate time series x
#Returns vector of eigenvalues after that you are on your own.
#This is a modified version for R, in which rts is substituted by ts. 
        x <- ts(x)
        n <- nrow(x)
        p <- ncol(x)
        Ly <- lag(x[, 1], -1)
        D <- diff(x[, 1])
        for(i in 1:p) {
                if(i > 1) {
                        D <- ts.intersect(D, diff(x[, i]))
                        Ly <- ts.intersect(Ly, lag(x[, i], -1))
                }
                if(L > 0)
                        for(j in 1:L)
                                D <- ts.intersect(D, lag(diff(x[, i]),  - j))
        }
        iys <- 1 + (L + 1) * (0:(p - 1))
        Y <- D[, iys]
        X <- D[,  - iys]
        Ly <- ts.intersect(Ly, D)[, 1:p]
        ZD <- lm(Y ~ X)$resid
        ZL <- lm(Ly ~ X)$resid
        df <- nrow(X) - ncol(X) - 1
        S00 <- crossprod(ZD)/df
        S11 <- crossprod(ZL)/df
        S01 <- crossprod(ZD, ZL)/df
        M <- solve(S11) %*% t(S01) %*% solve(S00) %*% S01
        eigen(M)$values
}

