Help with code. How to find the length of gaps with missing values in a matrix

This is the code and is not working as intended, the code is suposed to tell me if there is any adjacente NA values in a given column and how many. This is done by checking if a current value is NA and if the previous is NA as well, if this is the case, the will be a counter that will be registering this and saving the count in a new matrix, so at the end i will only search for the biggest value in every column and i will know how long is the longest chain of NA values.

#datos is the name of a matrix from excel

this part is to obtain the dimensions of the matrix

filas <- nrow(datos)
columnas <- ncol(datos)

#Creating a matrix to save the results
resultado <- matrix(0, nrow=filas, ncol=columnas)

counter at 0

contador <- matrix(0, 1, 1)

#going for every column
for (i in 1:columnas) {

going down at the current column

for (j in 1:filas) {
# verifying if the current value is NA
if ([j,i])) {
# verifying if the preious value is NA
if (j > 1 &&[j-1,i])) {
# if the previous value is NA, +1 to the counter
contador[1,1] <- contador[1,1] + 1
} else {
# if is not, counter restarts at 1
contador[1,1] <- 1
} else {
# if the value is not NA, restart the counter at cero
contador[1,1] <- 0
# savinf every value to the results matrix
resultado[j,i] <- contador[1,1]

show the matrix with the results


I hope that my idea is clearly explained here.

The problem is that you do not store the maximum value of contador as you move down the column. Imagine that the column starts with 5 consecutive NA values but then there are no more NAs. At the bottom of the column, contador will have a value of zero and that will be stored in resultado.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.