Skip to content
Prev 246853 / 398502 Next

Creating a Matrix from a vector with some conditions

On Thu, Jan 06, 2011 at 01:34:31PM -0800, ADias wrote:
Try the following

  v <- rep(c("a", "b", "c", "d"), times=2)
  a <- matrix(nrow=4, ncol=4)
  a[, ] <- v[row(a) + col(a) - 1]
  a
       [,1] [,2] [,3] [,4]
  [1,] "a"  "b"  "c"  "d" 
  [2,] "b"  "c"  "d"  "a" 
  [3,] "c"  "d"  "a"  "b" 
  [4,] "d"  "a"  "b"  "c" 

Petr Savicky.