21

How can I convert lon-lat points to simple features (sfg), and then put them in a simple feature collection (sfc)?

Here is a MWE that doesn't work but is the closest I have gotten to.

library(data.table)
library(sf)
# The DT data.table is the data I have (but 10,000s of rows, each row is a point)
DT <- data.table(
    place=c("Finland", "Canada", "Tanzania", "Bolivia", "France"),
    longitude=c(27.472918, -90.476303, 34.679950, -65.691146, 4.533465),
    latitude=c(63.293001, 54.239631, -2.855123, -13.795272, 48.603949),
    crs="+proj=longlat +datum=WGS84")
DT[, rowid:=1:.N]
# The following two rows do not work
DT[, place.sfg:=st_point(x=c(longitude, latitude), dim="XY"), by=rowid]
places.sfc <- st_sfc(DT[, place.sfg], crs=DT[, crs])
# This should result in five points, which it doesn't
plot(places.sfc)

I'm trying to learn Simple Features (which is why I do not want to use library sp), and later need to run st_buffer on the sfc.

Maybe better to create the sfc directly, without an sfg per point?

I use data.table for speed-reasons (10,000s of thousands of points that are also analysed without geographical aspects).

I think I need an sfc of sfg-points, and not a MULTIPOINT-sfg.

33

Have you tried st_as_sf() which converts object (sp, dataframe, ...) to an sf object?

library(data.table)
library(sf)
# your data (removed crs column)
DT <- data.table(
                 place=c("Finland", "Canada", "Tanzania", "Bolivia", "France"),
                 longitude=c(27.472918, -90.476303, 34.679950, -65.691146, 4.533465),
                 latitude=c(63.293001, 54.239631, -2.855123, -13.795272, 48.603949))
# st_as_sf() ######
# sf version 0.2-7
DT_sf = st_as_sf(DT, coords = c("longitude", "latitude"), 
                 crs = 4326, relation_to_geometry = "field")
# sf version 0.3-4, 0.4-0
DT_sf = st_as_sf(DT, coords = c("longitude", "latitude"), 
                 crs = 4326, agr = "constant")
plot(DT_sf)

As commented by @cengel, it would be important to keep up with rapid development of this package.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.