Skip to content

Instantly share code, notes, and snippets.

@MilesMcBain
Last active April 30, 2020 00:54
Show Gist options
  • Save MilesMcBain/57e722b75e58778bdc42f94260f6fb15 to your computer and use it in GitHub Desktop.
Save MilesMcBain/57e722b75e58778bdc42f94260f6fb15 to your computer and use it in GitHub Desktop.
lon_lat_to_point
##' Create an sf POINT column from long and lat columns
##'
##' This is a vectorised function that takes 2 columns of longitude and latitude
##' as arguments and returns a simple features geometry collection column in the
##' EPSG 4326 coordinate reference system (lon, lat).
##'
##' @title lon_lat_to_point
##' @param lon a numeric column of longitudes
##' @param lat a numeric column of latitudes
##' @return a simple features collection column of POINT geometries representing the lon/lat pairs.
##' @author Miles McBain
##' @export
lon_lat_to_point <- function(lon, lat) {
purrr::map2(
lon,
lat,
~ sf::st_point(c(.x, .y))
) %>%
sf::st_sfc(crs = 4326)
}
@dcooley
Copy link

dcooley commented Apr 29, 2020

Hey Miles.

I found this gist while exploring your hex-binning example and thought you might be interested in a sfheaders version of this code

n <- 1e5
df <- data.frame(
  x = rnorm(n)
  , y = rnorm(n)
)

sf1 <- lon_lat_to_point( df$x, df$y )
sf2 <- sfheaders::sfc_point(obj = df, x = "x", y = "y")

sf1
sf2

microbenchmark::microbenchmark(
  purr = { lon_lat_to_point( df$x, df$y ) },
  sfh = { sfheaders::sfc_point( obj = df, x = "x", y = "y" ) },
  times = 5
)

# Unit: milliseconds
# expr        min         lq       mean     median         uq        max neval
# purr 2578.57222 2642.97478 2702.92231 2694.57278 2794.98681 2803.50493     5
# sfh    27.45589   28.59706   32.75319   29.49304   30.67185   47.54809     5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment