I'm working with some large matrices with values along a diagonal similar to the following.
ontrack <- matrix(c(
runif(1),NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
runif(1),NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,runif(1),NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,runif(1),runif(1),NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,runif(1),NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,
NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,runif(1)),
nrow=14, byrow=T
)
I would like to fill in data gaps of length 'n' or less to connect segments of the diagonal. Using the above matrix for example and filling in data gaps of 3 or less, I would like to go from this:
diag_indx <- which(!is.na(ontrack), arr.ind=T)
which gives
row col
[1,] 1 1
[2,] 2 1
[3,] 3 3
[4,] 7 5
[5,] 7 6
[6,] 9 8
[7,] 14 13
to this
row col
1 1
2 1
newV 3 2
3 3
new 4 4
new 5 4
new 6 4
7 5
7 6
new 8 7
9 8
14 13
For instances like newV
, the result can be (2,2) or (3,2). My subsequent code uses the diag_indx
matrix but data gaps could be filled in the ontrack
matrix directly (using any value is ok) if it is more efficient.
In trying to work out a solution, I was envisioning finding the data gaps in the diag_indx
matrix using this sequence length equation
seqle <- function(x, incr=1) {
if(!is.integer(x)) x <- as.integer(x)
n <- length(x)
y <- x[-1L] != x[-n] + incr
i <- c(which(y|is.na(y)),n)
list(lengths = diff(c(0L,i)),
values = x[head(c(0L,i)+1L,-1L)])
}
and then filling in the data gaps using seq()
. I'm just not sure how to put it all together efficiently. Thank you for your help.