[英]Create sf object from two-column matrix
I have a simple two-column matrix that I want to convert to an sf
object where each row specifies a point: 我有一个简单的两列矩阵,我想将其转换为一个
sf
对象,其中每一行都指定一个点:
> set.seed(123);m=matrix(runif(10),ncol=2)
> m
[,1] [,2]
[1,] 0.2875775 0.0455565
[2,] 0.7883051 0.5281055
[3,] 0.4089769 0.8924190
[4,] 0.8830174 0.5514350
[5,] 0.9404673 0.4566147
The naivest approach doesn't work, as apply
mashes the points back together into a matrix and the operation just becomes a very slow transpose function: 最幼稚的方法行不通,因为
apply
将点混回到一个矩阵中,该操作变成了一个非常慢的转置函数:
> apply(m,1,st_point)
[,1] [,2] [,3] [,4] [,5]
[1,] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
[2,] 0.0455565 0.5281055 0.8924190 0.5514350 0.4566147
Best I can come up with without doing an explicit loop is this monster: 我最想出的就是不做显式循环的是这个怪物:
> st_sfc(lapply(data.frame(t(m)),st_point))
Geometry set for 5 features
geometry type: POINT
dimension: XY
bbox: xmin: 0.2875775 ymin: 0.0455565 xmax: 0.9404673 ymax: 0.892419
epsg (SRID): NA
proj4string: NA
POINT(0.287577520124614 0.0455564993899316)
POINT(0.788305135443807 0.528105488047004)
POINT(0.4089769218117 0.892419044394046)
POINT(0.883017404004931 0.551435014465824)
POINT(0.940467284293845 0.456614735303447)
The other option is to go via sp
objects, but I don't want to do that. 另一个选择是通过
sp
对象,但是我不想这样做。 I'd also like a solution in base R only, so no conversion to data.table or tbl etc. 我也只想在base R中使用解决方案,因此不转换为data.table或tbl等。
Am I just missing a simple as(m,"sf")
function or suchlike? 我只是缺少一个简单的
as(m,"sf")
函数或类似函数吗?
You can use the sfheaders
library on matrices directly 您可以直接在矩阵上使用
sfheaders
库
sfheaders::sf_point(m)
# Simple feature collection with 5 features and 0 fields
# geometry type: POINT
# dimension: XY
# bbox: xmin: 0.2875775 ymin: 0.0455565 xmax: 0.9404673 ymax: 0.892419
# epsg (SRID): NA
# proj4string: NA
# geometry
# 1 POINT (0.2875775 0.0455565)
# 2 POINT (0.7883051 0.5281055)
# 3 POINT (0.4089769 0.892419)
# 4 POINT (0.8830174 0.551435)
# 5 POINT (0.9404673 0.4566147)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.