2

I am running a loop in R to rasterize a list of data frames and for comparison purposes I have to keep the same list length in the output.

I am facing some problems with NULL objects on the list. I managed to handle NULL objects inside the list with tryCatch, however when I have null objects at the end of the list (e.g. last 3 objects) they are not included in the output of the loop, so the output list (fry) get shorter than the original list (fr.fr). See the output below.

I would like to know if there is an efficient way to handle this problem in R and to ensure the same list length. I also looking to more straightforward approaches.

Here is my code:

# Raster 
st <- raster(xxx)

# List of data frame to Raster
fry <- list()

for (i in 1:length(fry.fr)){
  tryCatch({
    fry[[i]] <- rasterize(fry.fr[[i]], st, fry.fr[[i]]$AREA, fun = sum, na.rm=FALSE)        
  }
  ,error= function(e) {cat("Error", "\n")})
}

Here is my output:

length(fry.fr) 336

length(fry) 333

2 Answers 2

2

initialise the list element to NA or some other flag value before you do the possibly failing computation:

for (i in 1:length(fry.fr)){
  fry[[i]] = NA # flag failure
  tryCatch({
    fry[[i]] <- rasterize(fry.fr[[i]], st, fry.fr[[i]]$AREA, fun = sum, na.rm=FALSE)        
  }
  ,error= function(e) {cat("Error", "\n")})
}

On success that NA gets overwritten, on fail it remains.

0

You can initialize the list so it has the correct length in the beginning. In your example this would look something like this:

fry <- vector (mode = "list", length (fry.fr))
1
  • It works very well! Tks
    – LFG
    Commented Jan 2, 2020 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.