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

counter at 0

#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 (is.na(datos[j,i])) {
# verifying if the preious value is NA
if (j > 1 && is.na(datos[j-1,i])) {
# if the previous value is NA, +1 to the counter
} else {
# if is not, counter restarts at 1
}
} else {
# if the value is not NA, restart the counter at cero
}
# savinf every value to the results matrix
}
}

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.