# Double indexing and looping over raster lists in R

I have a list of 63 rasters. They are the same extent, resolution, projection, etc. Because I extended 62 rasters to the maximum extent of the 63rd, I introduced NA values. However, these are relative probabilities so these introduced NAs are true zeros so I would like to convert all NAs to 0 for each raster element in the list.

I figured out how to do exactly what I want by double indexing with 1 raster:

``````# That worked for rast 8! Let's make a function​
sum(is.na(re[[8]][])) # 37000
re[[8]][][is.na(re[[8]][])] <- 0​
sum(is.na(re[[8]][])) # 0 ​
plot(re[[8]])         # Converted 0s appear light gray across max extent
``````

But I can't quite figure out how to perform the same indexing operation to all 63 rasters in my list. I tried the below function which I thought would work but I must not be indexing properly within the `lapply` loop because this function returns zero for each element in the list. So it's not working on the raster cells within each raster element.

``````re_zero <- lapply(re, function(y){
y[][is.na(y[])] <- 0
})
``````

I think this is perhaps just an indexing problem.

Could someone point me in the right direction?

Very simple solution below using a for-loop instead of `lapply`. However, I still don't know what I was doing wrong with the `lapply` function.

``````# Loop
for(i in 1:length(re)){

re[[i]][][is.na(re[[i]][])] <- 0
}
``````

This aproach shoud work:

``````re_zero <- list()
for(i in 1:length(re)){
r <- re[[i]]
r[is.na(r[])] <- 0
re_zero[[i]] <- r
}
``````
• `lapply` can be more efficient than a `for` loop in some cases. However, I don't think this is the case. I recommend using the `terra` package instead of `raster`, as it is more modern and efficient. This will make a difference. Also, `raster` is going to be discontinued soon. There is probably a better way to do this for a set of images stored in a terra catalog. Commented Sep 3, 2023 at 8:13