Looping through diagonal+1 of a matrix

matrix, r

Solution

You can index using a matrix.

eg

m <- matrix(1:25, ncol = 5)

The off diagonals can be accessed using

offd <- cbind(1:4,2:5)


m[offd]

## [1]  6 12 18 24

You could create a function that does this

offdiag <- function(m, offset){
  i <- seq_len(nrow(m)-offset)
  j <- i + offset
  m[cbind(i,j)]

}


offdiag(m, 1)
## [1]  6 12 18 24
offdiag(m, 2)
[1] 11 17 23
offdiag(m, 3)
## [1] 16 22
offdiag(m, 4)
## [1] 21

Problem

I need to loop through the diagonal+1 (i.e. the values 1 column to the right of the diagonal) and write the value to a column in a dataframe: ``` write.csv(data.frame(matrix[1,2], matrix[2,3], matrix[3,4]) ``` How can I do this using a function, rather than just listing all the positions of the values?

Original source