hrbrmstr / mgrs

:globe_with_meridians: An R Package to Convert 'MGRS' (Military Grid Reference System) References From/To Other Coordiante Systems
Other
30 stars 8 forks source link

Feature Request: Passing Data Frames to mgrs_to_latlng #2

Closed gl-smith closed 5 years ago

gl-smith commented 5 years ago

I was wondering if you had given any thought into making it possible to use columns from a data frame as the input to themgrs_to_latlng function rather than just strings? This would make it possible to use the function directly within a mutate call. I have included the code to a rough function that makes it possible to convert vectors to lat and long coordinates. Thanks for all the work that you've put into this package. It's really helpful!

#----- Function

mgrs_df_convert <- function(df, mgrs_coord_vector, coord) {

  library(mgrs)

  utm_vector <- df[[mgrs_coord_vector]]
  lat_long_vectors <- mgrs::mgrs_to_latlng(utm_vector)
  lat_vectors <- lat_long_vectors[,c(2)]
  long_vectors <- lat_long_vectors[,c(3)]

  if (coord == "lat") {
    print(lat_vectors)
  } else if (coord == "long") {
    print(long_vectors)
  } else {
    print("Error: coord needs to specify lat or long")
  }

}

#---- Example 

sample_dta <- tibble(
  id = 1:4, 
  mgrs = c("48QYD448540", "48QYD454535", "48QYD458529", "48QYD442547")
)

mutate_test_dta <- sample_dta %>% 
  mutate(lat_test = mgrs_df_convert(., "mgrs", "lat"),
         long_test = mgrs_df_convert(., "mgrs", "long"))

glimpse(mutate_test_dta)
hrbrmstr commented 5 years ago

How does this sound:

sample_dta <- tibble(
  id = 1:4, 
  mgrs = c("48QYD448540", "48QYD454535", "48QYD458529", "48QYD442547")
)

mutate(sample_dta, x = map(mgrs, mgrs_to_latlng, include_mgrs_ref = FALSE)) %>% 
  unnest(x)
## # A tibble: 4 x 4
##      id mgrs          lat   lng
##   <int> <chr>       <dbl> <dbl>
## 1     1 48QYD448540  16.8  107.
## 2     2 48QYD454535  16.8  107.
## 3     3 48QYD458529  16.7  107.
## 4     4 48QYD442547  16.8  107.
gl-smith commented 5 years ago

That looks like a straightforward solution! What does the command include_mgrs_ref do? I didn't see it in the source documentation.

hrbrmstr commented 5 years ago

i didn't push it yet :-)

if you install_github("hrbrmstr/mgrs", ref="v0.2.0") (it's pushed now) you'll be able to test the new code (I also vectorized the other two data frame ops as well).

if include_mgrs_ref is TRUE the mgrs input string gets a column. that's horribad for unnesting since it's wasting space and ops, so setting it to FALSE just doesn't spit that column out.

hrbrmstr commented 5 years ago

If you could also have a look at https://github.com/hrbrmstr/mgrs/blob/v0.2.0/DESCRIPTION#L10-L11 to make sure it's ok (I can change any of it or remove it if you'd rather stay anonymous on CRAN as I'll be submitting it there next week) that'd be 👍

gl-smith commented 5 years ago

Oh great. That makes sense now. All the information you added looks right. Thanks for the help with this!