[R] elegant matrix creation

Gabor Grothendieck ggrothendieck at myway.com
Wed Jul 28 18:27:10 CEST 2004



[Sorry if this gets posted twice but I am having more gmane posting problems.]

Not sure if this qualifies as elegant or not but it does (1) bring
all three matrices under a single scheme, (2) reduce the number of
numbers from 81 to 18 per matrix, (3) requires only a single one
line utility function, (4) is simple and (5) gives some minimal
insight into the patterns.

The key thing to note is that each row of each matrix is a cyclic
shift of the first row of that matrix.

Define a shift function which shifts its vector argument v by 
shift positions to the left creating a one row matrix.  If shift is 
a vector it creates a matrix with one row per shift.

shiftL <- function(v, shift) 
	outer(shift,seq(along=v)-1, function(i,j)v[(i+j)%%length(v)+1])

jj1a <- shiftL(c(1,1,1,2,2,2,3,3,3),c(0,3,6,0,3,6,0,3,6))
jj2a <- shiftL(c(1,2,1,3,1,3,2,3,2),c(0,6,3,0,6,3,0,6,3))
jj3a <- shiftL(c(1,1,1,2,2,2,3,3,3),c(0,4,8,3,7,2,6,1,5))

# or finding expressions for the two args in each case:

jj1b <- shiftL( rep(1:3,c(3,3,3)), rep(c(0,3,6),3) )
jj2b <- shiftL( c(shiftL(c(1,3,2),c(0,2,0))), rep(c(0,6,3),3) )
jj3b <- shiftL( rep(1:3,c(3,3,3)), seq(0,32,4) %% 9 )




More information about the R-help mailing list