从两列矩阵创建 sf 对象 [英] Create sf object from two-column matrix
问题描述
我有一个简单的两列矩阵,我想将其转换为 sf
对象,其中每一行指定一个点:
I have a simple two-column matrix that I want to convert to an sf
object where each row specifies a point:
> 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
最简单的方法行不通,因为 apply
将点重新组合成一个矩阵,而操作只是变成了一个非常慢的转置函数:
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(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)
另一种选择是通过 sp
对象,但我不想这样做.我也想要一个只在基础 R 中的解决方案,所以没有转换为 data.table 或 tbl 等.
The other option is to go via sp
objects, but I don't want to do that. I'd also like a solution in base R only, so no conversion to data.table or tbl etc.
我是否只是缺少一个简单的 as(m,"sf")
函数或类似的函数?
Am I just missing a simple as(m,"sf")
function or suchlike?
推荐答案
根据 sf 文档
m %>%
as.data.frame %>%
sf::st_as_sf(coords = c(1,2))
这篇关于从两列矩阵创建 sf 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!