[R] matrix of higher order differences
    Jeroen Ooms 
    jeroenooms at gmail.com
       
    Wed Apr 27 08:23:22 CEST 2011
    
    
  
Is there an easy way to turn a vector of length n into an n by n matrix, in
which the diagonal equals the vector, the first off diagonal equals the
first order differences, the second... etc. I.e. to do this more
efficiently:
diffmatrix <- function(x){
	n <- length(x);
	M <- diag(x);
	for(i in 1:(n-1)){
		differences <- diff(x, dif=i);
		for(j in 1:length(differences)){
			M[j,i+j] <- differences[j]
		}
	}
	M[lower.tri(M)] <- t(M)[lower.tri(M)];
	return(M);
}
x <- c(1,2,3,5,7,11,13,17,19);
diffmatrix(x);
--
View this message in context: http://r.789695.n4.nabble.com/matrix-of-higher-order-differences-tp3477339p3477339.html
Sent from the R help mailing list archive at Nabble.com.
    
    
More information about the R-help
mailing list