[R-sig-Geo] extract X, Y coordinates from (points) POSTGIS coordinates (WKT

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon Apr 20 13:24:35 CEST 2015


If you install rgeos then you get the readWKT function, and use sp as
well to build some spatial points:

[tip: use `dput(d)` to dump sample data]

> d = structure(list(xy = c("POINT (-59.900833 -34.869722)", "POINT (-60.009032477477234 -34.71350213192503)",
"POINT (-60.13337136105485 -34.74472597084807)", "POINT
(-60.199859958706185 -34.7384738077165)"
)), .Names = "xy", row.names = c(NA, -4L), class = "data.frame")

 > library(sp); library(rgeos)

 > xy = do.call(rbind,lapply(d$xy, readWKT))
 > xy
SpatialPoints:
          x         y
1 -59.90083 -34.86972
1 -60.00903 -34.71350
1 -60.13337 -34.74473
1 -60.19986 -34.73847

You can then get the separate coordinates as vectors:

 > xy$x
        1         1         1         1
-59.90083 -60.00903 -60.13337 -60.19986
 > xy$y
        1         1         1         1
-34.86972 -34.71350 -34.74473 -34.73847

[the 1s are just row labels]

If you just want a 2-column matrix:

 > coordinates(xy)
          x         y
1 -59.90083 -34.86972
1 -60.00903 -34.71350
1 -60.13337 -34.74473
1 -60.19986 -34.73847

 - thats a matrix, not a data frame, but you can easily build one!

Barry



On Mon, Apr 20, 2015 at 11:01 AM, Marcos Angelini <angelini75 at gmail.com> wrote:
> Hi community,
>
> I have a data frame of points with coordinates (WKT) in one column. It is
>
> d <- as.data.frame(NULL)
> d$xy <- c("POINT (-59.900833 -34.869722)", "POINT (-60.009032477477234
> -34.71350213192503)", "POINT (-60.13337136105485 -34.74472597084807)",
> "POINT (-60.199859958706185 -34.7384738077165)")
>
> I want to convert this into:
> d$X
> -59.900833
> -60.009032
> -60.133371
> -60.199860
> d$Y
> -34.869722
> -34.713502
> -34.744726
> -34.738474
>
> I've tried with gsub() but I'm not handy with regular expressions. Could
> you help me, please?
>
> Marcos.
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



More information about the R-sig-Geo mailing list