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
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)
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.
Am I just missing a simple as(m,"sf")
function or suchlike?
As per the sf docs
m %>%
as.data.frame %>%
sf::st_as_sf(coords = c(1,2))
You can use the sfheaders
library on matrices directly
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With