RE: [R] elegant matrix creation

From: Gabor Grothendieck <ggrothendieck_at_myway.com>
Date: Thu 29 Jul 2004 - 03:12:21 EST

In reading this over I noticed that the two input vectors to shiftL could be put in a parameterized form that reduces the input to two integers:

shiftL <- function(v, shift)

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

jj <- function(i,j)

   shiftL( seq(0,by=i,len=9) %% 9 %/% 3 + 1, seq(0, len=9, by=j) %% 9)

jj1 <- jj(1,3)
jj2 <- jj(5,6)
jj3 <- jj(1,4)



From:   	Gabor Grothendieck <ggrothendieck@myway.com>

[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 )

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Thu Jul 29 03:19:50 2004

This archive was generated by hypermail 2.1.8 : Wed 03 Nov 2004 - 22:55:20 EST