1

Before I attempt writing a custom function; is there an elegant/native method to achieve this?

m<-matrix(1:9,ncol = 3)
m
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

By column:

as.vector(m)
[1] 1 2 3 4 5 6 7 8 9

By row:

as.vector(t(m))
[1] 1 4 7 2 5 8 3 6 9

By diagonal (I would like a function output):

some.function(m)
[1] 1 2 4 3 5 7 6 8 9

And the perpendicular diagonal:

some.other.function(m)
[1] 7 8 4 9 5 1 6 2 3
Brian Davis
  • 990
  • 5
  • 11
  • 1
    There's a pretty good solution that you can adapt to your question here: https://stackoverflow.com/questions/27935555/get-all-diagonal-vectors-from-matrix – Lamia Dec 18 '17 at 19:56

1 Answers1

1
ind = expand.grid(1:3, 1:3)
ind[,3] = rowSums(ind)
ind = ind[order(ind[,3], ind[,2], ind[,1]),]

m[as.matrix(ind[,1:2])]
#[1] 1 2 4 3 5 7 6 8 9

m[,3:1][as.matrix(ind[,1:2])]
#[1] 7 8 4 9 5 1 6 2 3
d.b
  • 32,245
  • 6
  • 36
  • 77