Reprex below.
Hoping to see a cleaner solution with pivot_longer()
than that illustrated below.
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(tidyr)
#> Warning: package 'tidyr' was built under R version 3.5.3
# input
df_raw <- tibble::tribble(
~off_loc, ~pt_loc, ~pt_lat, ~off_lat, ~pt_long, ~off_long,
"A", "G", 100.0754822, 121.271083, 4.472089953, -7.188632,
"B", "H", 75.191326, 75.93845266, -144.387785, -143.2288569,
"C", "I", 122.6513448, 135.043791, -40.45611048, 21.242563,
"D", "J", 124.1355333, 134.511284, -46.07156181, 40.937417,
"E", "K", 124.1355333, 134.484374, -46.07156181, 40.78472,
"F", "L", 124.0102891, 137.962195, -46.01594293, 22.905889
)
# desired output
df_long <- tibble::tribble(
~loc, ~lat, ~long,
"A", 121.271083, -7.188632,
"B", 75.93845266, -143.2288569,
"C", 135.043791, 21.242563,
"D", 134.511284, 40.937417,
"E", 134.484374, 40.78472,
"F", 137.962195, 22.905889,
"G", 100.0754822, 4.472089953,
"H", 75.191326, -144.387785,
"I", 122.6513448, -40.45611048,
"J", 124.1355333, -46.07156181,
"K", 124.1355333, -46.07156181,
"L", 124.0102891, -46.01594293
)
# current solution
df_raw %>%
pivot_longer(cols = c(contains('lat'), contains('long'))) %>%
pivot_longer(cols = contains('loc'), names_to = 'loc', values_to = 'loc_val') %>%
filter(str_remove(name, '_(lat|long)') == str_remove(loc, '_(loc)')) %>%
mutate(name = str_remove(name, '(off|pt)_')) %>%
spread(name, value) %>%
select(-loc)
Created on 2019-11-04 by the reprex package (v0.2.1)