0

I am using the 'try' function to create some subsets but I cannot manage to keep only the results taht worked with the 'try' function. Below is the line of code I have.

list_shp_Deforested_2000_Africa <- lapply(list_shp_FC_Africa, function(x){try(x[x$D_90_00!=100,],)})

Does somebody know the function which will allow me to keep only the result that worked? Thanks for your help?

Simon Besnard
  • 377
  • 1
  • 6
  • 18

2 Answers2

1

When you ask about the try function, you should read help(try) first. The last line in the examples does what you are interested in (where you should substitute list_shp_Deforested_2000_Africa for res).

unlist(res[sapply(res, function(x) !inherits(x, "try-error"))])
shadow
  • 21,823
  • 4
  • 63
  • 77
1

You can Filter the list to not include those that inherit "try-error"

Filter(function(x) !inherits(x, "try-error"), list_shp_Deforested_2000_Africa)

Or, if you used tryCatch and return NULL if there is an error, it might be cleaner

L <- lapply(1:10, function(x) tryCatch(if(runif(1) > 0.5) stop() else 42, error=function(e) NULL))
Filter(length, L)    
GSee
  • 48,880
  • 13
  • 125
  • 145