R中的Lon-Lat到简单功能(sfg和sfc)


20

如何将lon-lat点转换为简单要素(sfg),然后将其放入简单要素集合(sfc)中?

这是一个不起作用的MWE,但它是我所获得的最接近的MWE。

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)

我正在尝试学习“简单功能”(这就是为什么我不想使用库sp),后来需要在sfc上运行st_buffer。

也许最好直接创建sfc,而无需每点sfg?

我将data.table用于速度原因(也分析了数十万个点,没有地理方面的影响)。

我想我需要一个sfg点的sfc,而不是MULTIPOINT-sfg。


:类似的问题,有人问SO stackoverflow.com/questions/29736577/...
andschar

Answers:


32

您是否尝试过将对象(sp,dataframe等)转换为sf对象的st_as_sf()

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)

[更新]正如cengel所说,跟上该程序包的快速开发很重要。


2
运行此代码给我一个错误:Error in st_sf(x, ..., agr = agr) : no simple features geometry column present
cengel

2
@cengel谢谢指出。当我发布此答案(2017年1月)时,sf软件包的版本为0.2-7,其中使用了Relation_to_geometry参数。我确认最新的科幻小说(0.3-4:2017年3月)抛出了您评论中的错误。现在参数必须是agr(如@ jeffrey-evans所评论)。
Kazuhito
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.