Consider the following matrix,
m <- matrix(letters[c(1,2,NA,3,NA,4,5,6,7,8)], 2, byrow=TRUE)
## [,1] [,2] [,3] [,4] [,5]
## [1,] "a" "b" NA "c" NA
## [2,] "d" "e" "f" "g" "h"
I wish to obtain the column indices corresponding to all non-NA elements, merged with the NA elements immediately following:
result <- c(list(1), list(2:3), list(4,5),
list(1), list(2), list(3), list(4), list(5))
Any ideas?
The column (and row) indicies of non-NA elements can be obtained with
A full answer:
Since you want to work row-wise, but R treats vector column-wise, it is easier to work on the transpose of
m.We get the array indicies as mentioned above, which gives the start point of each list.
Since we are working on the transpose, we want the row indices, and we need to deal with each column separately.
The length of each list is given by the difference between starting points, or the difference between the last point and the end of the row (+1). Then we just call
seqto get a sequence.