alathrop
10/24/2017 - 11:45 AM

Sort rows by new index

# data frame of UTM and long/lat coords
# with zone and bearing
# ordered by increasing bearing within each zone
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
c_coords_df <- c_coords_longlat %>% 
  map_df(
    ~ as.data.frame(.x),
    .id = "zone"
  ) %>% 
  
  rename(
    x_long = X,
    y_lat = Y
  ) %>% 
  
  mutate(
    index = row_number()
  ) %>% 
  
  # add bearing values
  left_join(c_bearings_df) %>% 
  
  # add UTM coords
  left_join(c_coords_UTM_df) %>% 
  
  # sort by increasing bearing within each zone
  group_by(zone) %>%
  
  mutate(
    zone_rows = n(),
    zone_index = row_number(),
    bearing_min = which.min(bearing),
    index_bearing = case_when(
      zone_index < bearing_min ~ zone_rows - bearing_min + zone_index + 1,
      zone_index >= bearing_min ~ zone_index - bearing_min + 1)
  ) %>% 
  
  ungroup %>% 

  arrange(zone, index_bearing) %>% 
  
  # re-index
  mutate(
    index = row_number()
  ) %>% 
  
  select(index, zone, bearing, everything(), -c(zone_rows, zone_index, bearing_min))
  
  # tmp <- bind_rows(l_c_coords[[2]])
# tmp <- tmp %>%
#   mutate(index = row_number(),
#          which_x = first(which(x == UTM_coords$X)),
#          index_x = case_when(
#            index <=  which_x ~ which_x - row_number() + 1,
#            index >   which_x ~ nrow(.) - row_number() + which_x + 1)) %>%
#   arrange(index_x) 

# tmp <- bind_rows(l_c_coords[[2]])
# tmp <- tmp %>%
#   mutate(index = row_number(),
#          which_x = first(which(x == UTM_coords$X)),
#          index_x = case_when(
#            index <  which_x ~ index + nrow(.) - which_x + 1,
#            index >= which_x ~ row_number() - which_x + 1)) %>%
#   arrange(index_x)
# 
# ###
# 
# tmp <- bind_rows(l_c_coords[[2]])
# tmp <- tmp %>%
#   mutate(index = row_number(),
#          index_y = case_when(
#            index <  which.max(y) ~ index + nrow(.) - which.max(y) + 1,
#            index >= which.max(y) ~ row_number() - which.max(y) + 1 )) %>%
#   arrange(index_y)