We know that apply() in base can apply a function to margins of an array, and margins should be rows or columns. I want to expand the margins to "diagonals" and "anti-diagonals". The structure looks like
diagApply <- function(x, FUN, ..., anti = FALSE) { }
I name this function diagApply and the argument anti is an indicator of "diagonals" and "anti-diagonals" which FUN will be applied over (defaults to FALSE). Take a 3x4 matrix for example:
mat <- matrix(letters[1:12], 3, 4)
# [,1] [,2] [,3] [,4]
# [1,] "a" "d" "g" "j"
# [2,] "b" "e" "h" "k"
# [3,] "c" "f" "i" "l"
Assume that I need to paste elements in each (anti-)diagonal. With an apply()-like way, the function should be executed as
diagApply(mat, paste, collapse = ".") # code 1
diagApply(mat, paste, collapse = ".", anti = TRUE) # code 2
The expected output will be
list("c", "b.f", "a.e.i", "d.h.l", "g.k", "j") # output of code 1
list("a", "d.b", "g.e.c", "j.h.f", "k.i", "l") # output of code 2
Are there any existing functions achieving that? If not, hope someone can share your idea on this issue. Thanks in advance!