Get positions for NA only in the "middle" column of the matrix

I want to get an index that refers to the positions of the NA values โ€‹โ€‹in the matrix, where the index is true if the given cell is NA and there is at least one non-NA value before and after it in the column. For example, given the following matrix

     [,1] [,2] [,3] [,4]
[1,]   NA    1   NA    1
[2,]    1   NA   NA    2
[3,]   NA    2   NA    3

the only value of the index returning TRUE should be [2,2].

Is there a compact expression for what I want to do? If I had to go through the columns and use something like min(which(!is.na(x[,i]))), to find the first value other than NA in each column, and then set all the values โ€‹โ€‹before that to FALSE (and the same for all values โ€‹โ€‹after max). Thus, I would not choose the start and end values โ€‹โ€‹of NA. But this seems a little dirty, so I wonder if there is a cleaner expression that does this without loops.

EDIT To be valid, an NA value must have a non-NA value before and after it somewhere inside the column, but not necessarily next to it. For example, if a column was defined with c (NA, 3, NA, NA, NA, 4, NA), the NA that I want to find will be at positions 3, 4 and 5, since they are enclosed in non-NA.

+5
3

, :

z <- matrix(c(NA,1,NA,1,NA,2,NA,NA,NA,1,2,3),ncol=4)
isNA <- is.na(z)
# Vertical index which increments at non-NA entries, counting top-to-bottom:
nonNA_idx.tb <- apply(!isNA, 2, cumsum)
# Vertical index which increments at non-NA entries, counting bottom-to-top:
nonNA_idx.bt <- apply(!isNA, 2, function(x) { rev(cumsum(rev(x))) })
which(isNA & nonNA_idx.tb>0 & nonNA_idx.bt>0, arr.ind=TRUE)

(PS - , , )

+4
m <- matrix(c(NA, 1, NA, 1, NA, 2, NA, NA, NA, 1, 2, 3), ncol= 4)

matmain <- is.na(m)
matprev <- rbind(FALSE, head(!matmain, -1))
matnext <- rbind(tail(!matmain, -1), FALSE)

which(matmain & (matprev | matnext), arr.ind = TRUE)

. , , - ? [2,1] [3,1] [2,2], [2,3]?

m <- matrix(c(1, NA, NA, 5, 1, NA, 3, 5, 4, NA, NA, NA, 1, 2, 3, 5), ncol= 4)
+1

pts <- sample (c (1:10, NA), size = 100, replace = T)

mat <- matrix (pts, ncol = 10)

which (is.na (mat), arr.ind = T)

0
source

All Articles