jmsigner / amt

37 stars 13 forks source link

Any tryCatch type function for failed smoothing parameter calculations #21

Closed coverton-usgs closed 4 years ago

coverton-usgs commented 4 years ago

I have a large set of tracks (several thousand) that I am trying to calculate kde's for. When running code to produce the kde and HR-area estimates some individuals fail to produce smoothing parameter estimates, rightfully so in most cases. Is there a way to "skip" those?

I can run all individuals with locoh methods just fine. (And I just plain gave up on calculating lscv for now)

kdepifunc<-function(x) {
  x %>% hr_kde(h=hr_kde_pi(.),trast = raster(as_sp(.), nrow = 1000, ncol = 1000), levels = c(0.5, 0.95), rand_buffer = 10)
}  

#works on first few individuals
z1<-alltracks_data_30m[1:2,]%>%  mutate(kde_pi = map(trk, kdepifunc)) %>%  mutate(kde_pi_area = map(kde_pi, function(x) x %>% hr_area()))

#does not work on all individuals
z3<-alltracks_data_30m%>%  mutate(kde_pi = map(trk, kdepifunc)) %>%  mutate(kde_pi_area = map(kde_pi, function(x) x %>% hr_area()))

Error in sp::SpatialPolygonsDataFrame(con, df) : Object length mismatch: con has 1 Polygons objects, but df has 2 rows

The only work around I can think of is looping a tryCatch in but for loops sound like a poor substitute. Is there a way to insert the tryCatch into th piped commands?

coverton-usgs commented 4 years ago

I need to push myself more before submitting requests apparently.

z1<-tryCatch(z %>%  mutate(kde_pi = map(trk, kdepifunc)) %>%  mutate(kde_pi_area = map(kde_pi, function(x) x %>% hr_area())), error=function(cond){return(NA)})

works

jmsigner commented 4 years ago

I think you could also use the following:

library(purrr)
z1 <- z %>%  mutate(kde_pi = map(trk, ~ safely(kdepifunc(.x) %>% hr_area(), otherwise = NA)))

But see also here: https://www.rdocumentation.org/packages/purrr/versions/0.2.5/topics/safely

coverton-usgs commented 4 years ago

Thank you very much Johannes, I am not familiar with purrr yet that helps a lot.

All the best, Cory


From: Johannes Signer notifications@github.com Sent: Thursday, June 11, 2020 9:24 PM To: jmsigner/amt amt@noreply.github.com Cc: Overton, Cory T coverton@usgs.gov; State change state_change@noreply.github.com Subject: [EXTERNAL] Re: [jmsigner/amt] Any tryCatch type function for failed smoothing parameter calculations (#21)

I think you could also use the following:

library(purrr) z1 <- z %>% mutate(kde_pi = map(trk, ~ safely(kdepifunc(.x) %>% hr_area(), otherwise = NA)))

But see also here: https://www.rdocumentation.org/packages/purrr/versions/0.2.5/topics/safely

— You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHubhttps://github.com/jmsigner/amt/issues/21#issuecomment-643057216, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AKMPO6W2QUATORGTPT2K4QTRWGUX3ANCNFSM4N3YTXRQ.