[R] matrix of higher order differences

From: Jeroen Ooms <jeroenooms_at_gmail.com>
Date: Tue, 26 Apr 2011 23:23:22 -0700 (PDT)

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)];


x <- c(1,2,3,5,7,11,13,17,19);

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.

R-help_at_r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Wed 27 Apr 2011 - 06:35:21 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 27 Apr 2011 - 11:40:33 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive