Search code examples
rmatrixgeospatialinfinite

In R, how can I identify the specific cells that contain INFINITE values in my inverse distance matrix?


The context: I'm using the ape package to calculate Moran's I, cannibalizing the procedure identified here. I keep getting this error:

Error in if (obs <= ei) 2 * pv else 2 * (1 - pv) : missing value where TRUE/FALSE needed

Rooting around on Stack Overflow and the Internet, I have found some suggestions that this error can result from having infinite values or NA values. When I run sum(is.infinite(inv.coord.distances)) I still end up with four infinite values. Using sum(is.na()), sum(is.nan()) and sum.is(null()) returns zero of those potential problems. When I manually search my 93x93 matrix, I do not see any INF values, though this method is not fool-proof. Nonetheless, I keep getting this error and my sum(is.infinite()) operation keeps telling me there are four infinite values. This happens whether I use UTM or latitude and longitude.

My question: Is there a command that returns the cell location of all my infinite values in my matrix? I tried which(inv.coord.distances != inf), but evidently which() will not find infinite values in a matrix.


Solution

  • The answer: To identify the specific cell or cells that contain INFINITE values in an inverse distance matrix, I used...

    which(is.infinite(inv.coord.distances))

    as suggeted by [dww].

    To convert the cells returned to their rows and columns, divide the value by the number of columns in a row. The whole number is the row number. Next, multiply the proportion left over by the number of columns in a row. This identifies the column.

    For instance, 1008 was one of my four cells containing the INF value. 1008/93 = 10.83871. This cell is located in row 10 and column 78 (since 0.83871* 93 = 78.00003).

    The tidyverse solution provided by [OftenOverkilledSolutions] should alse reveal the offending cells:

    as_tibble(inv.coord.distances) %>% mutate(row = row_number()) %>% gather(Column,Value,-row) %>% filter(is.na(Value)) #Or some other condition here