Search code examples
rrasterna

R: Can't replace NAs with zeros in vector


I know that topic arose plenty of times in the past as it is found multiple times via google search. But somehow I can't replace NAs in a vector with zeros, instead all values get overwritten.

I wanted to do some kmeans clustering following this guide. As I proceeded to the step where I have to use the setValues() function, I recognized that the length between both inputs differs. I thought that the reason for that are some NA Values, so I checked if there are NAs and if true, to overwrite them with zeros.

To check I did:

sum(is.infinite(nr))
sum(is.na(nr))
sum(is.nan(nr))

After that I knew that there are some NAs. So I followed this SO. After typing:

nr_2 <- nr[!is.finite(nr)] <- 0

All values got overwritten with zeros. So I checked the data type of nr. RStudio stated 'Large Numeric' and after typing is.vector(nr) it returned TRUE. Did I something wrong with indexing? So I tried to extract a single value with nr[1] and I got what I expected. But I also tried nr[[1]] and it worked also and returned the same value. And at that point some explanation would be great.

But the main question remians, why I can't replace NAs with zeros.


Solution

  • Given that you are dealing with a raster object, presumably a RasterLayer

    library(raster)
    r  <- raster(nrow=10, ncol=10, values=1:100)
    r[1:10] = NA
    

    Now you can do (my preference)

    d <- reclassify(r, cbind(NA, 0))
    

    Or the below approaches (which are meant for quick interactive operations on smaller objects)

    r[is.na(r)] <- 0
    

    Or

    r[!is.finite(r)] <- 0