user5306293
user5306293

Reputation:

Breaking down segment formed by map coordinates into parts

I have the following coordinates in a dataframe

origin_lon    origin_lat    dest_lon    dest_lat
<dbl>         <dbl>         <dbl>       <dbl>
-84.42778     33.63667      -87.90667   41.9744

I want to create a new dataframe by dividing the line segment formed by joining those coordinates into an equal number of parts(as defined).

longitude    latitude
-84.42778    33.63667
   ...         ...
-87.90667    41.9744

I am trying to achieve this using the following

tibble(longitude=-84.42778:-87.90667, latitude=33.63667:41.9744)

But am not sure if this is correct.

Upvotes: 0

Views: 77

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

You can try this method using dplyr and tidyr :

library(dplyr)
library(tidyr)
n <- 10

df %>%
  pivot_longer(cols = everything(), 
               names_to = c('col', '.value'),
               names_sep = '_') %>%
   select(-col) %>%
   summarise(lon = list(seq(max(lon), min(lon), length.out = n)), 
              lat = list(seq(min(lat), max(lat), length.out = n))) %>%
   unnest(cols = c(lat, lon))


# A tibble: 10 x 2
#     lon   lat
#   <dbl> <dbl>
# 1 -84.4  33.6
# 2 -84.8  34.6
# 3 -85.2  35.5
# 4 -85.6  36.4
# 5 -86.0  37.3
# 6 -86.4  38.3
# 7 -86.7  39.2
# 8 -87.1  40.1
# 9 -87.5  41.0
#10 -87.9  42.0

Here we first get data in long format where latitude and longitude are there in their respective columns. We then create a sequence between max and min value in those columns respectively with output of length n.

data

df <- structure(list(origin_lon = -84.42778, origin_lat = 33.63667, 
dest_lon = -87.90667, dest_lat = 41.9744), class = "data.frame", 
row.names = c(NA, -1L))

Upvotes: 1

Related Questions