[R] Extract entries from matrix
Jorge I Velez
jorgeivanvelez at gmail.com
Tue Oct 27 19:43:26 CET 2015
Dear R-help,
I am working with a matrix "m" from which I would like to extract some
elements. An toy example is as follows:
## input matrix
m <- structure(c(0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 0L,
0L, 0L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L), .Dim = c(22L, 5L))
R> m
# [,1] [,2] [,3] [,4] [,5]
# [1,] 0 0 0 0 0
# [2,] 0 0 0 0 0
# [3,] 0 0 0 0 0
# [4,] 1 2 3 0 0
# [5,] 1 2 3 0 0
# [6,] 1 2 3 0 0
# [7,] 1 2 3 0 0
# [8,] 1 2 3 0 0
# [9,] 1 2 3 4 0
# [10,] 1 2 3 4 0
# [11,] 1 2 3 4 5
# [12,] 1 2 3 4 5
>From "m", I would like to extract the entries
4, 1
5, 2
6, 3
7, 1
8, 2
9, 3
10, 1
11, 2
12, 3
so at the end of applying a function "f" to "m" I get
1, 2, 3, 1, 2, 3, 4, 1, 2, 3
Basically the idea is to extract the diagonal elements until a zero is
found.
In the real problem the dimensions of "m" are much bigger, but this smaller
version of "m" illustrate what needs to be done.
I would greatly appreciate any ideas on how to do this.
Thanks in advance,
Jorge Velez.-
[[alternative HTML version deleted]]
More information about the R-help
mailing list