Reputation: 1
I have a data frame in R, with some coordinates in EPSG 25832 system. I have tried some different things to convert the class to a spatial point, but I can't get it to work.
Geometri_EPSG_25832 | Var1 | Var2 |
---|---|---|
POINT (549611.77 6189284.79) | 1.99 | 739 |
POINT (700990.83 6223807.37) | 12 | 129 |
I have then tried something from another post: Error "OGR: Unsupported geometry type" when using st_as_sfc from sf package in R
# Remove "POINT" and parentheses
Total_df$EPSG <- gsub("POINT|\\(|\\)", "", Total_df$Geometri_EPSG_25832)
Total_df$EPSG <- sf::st_as_sfc(Total_df$EPSG,CRS("+init=epsg:25832"))
# Convert to numeric values
Total_df$x_coord <- as.numeric(stringr::str_extract(Total_df$EPSG, "[^ ]+"))
Total_df$y_coord <- as.numeric(stringr::str_extract(Total_df$EPSG, "(?<=\\s)[^\\s]+"))
Total_df$Coor <- paste0(Total_df$x_coord,", ", Total_df$y_coord)
Total_df$geos_points <- sapply(Total_df$Coor, function(x) st_multipoint(matrix(eval(str2lang(x)), ncol = 2)), USE.NAMES = FALSE)
But then get an: Error in parse(text = x) : :1:10: unexpected ',' 1: 549611.77, ^
Upvotes: 0
Views: 145
Reputation: 1
@VinceGreg, but your suggestion was the missing piece. I thank you very much. I ran Total_df$Coor[!grepl("^POINT", Total_df$Coor)] to detect if any observations started without "POINT", then made sure it all had the same format, and then I could apply st_as_sfc with ease. Thank you!
Upvotes: 0
Reputation: 834
Your dataframe seems to have a geometry in Well-known text format (WKT). sf
is supporting that format.
I just saw the answer of margusl. I think that we can do everything in the same st_as_sf
call.
library(sf)
#> Linking to GEOS 3.11.2, GDAL 3.7.2, PROJ 9.3.0; sf_use_s2() is TRUE
df =data.frame( Geometri_EPSG_25832 = c("POINT (549611.77 6189284.79)" ,
"POINT (700990.83 6223807.37)"),
Var1 = c(1.99,12) , Var2 = c(739,129))
st_as_sf(df, wkt="Geometri_EPSG_25832", crs = 25832 )
#> Simple feature collection with 2 features and 2 fields
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 549611.8 ymin: 6189285 xmax: 700990.8 ymax: 6223807
#> Projected CRS: ETRS89 / UTM zone 32N
#> Var1 Var2 Geometri_EPSG_25832
#> 1 1.99 739 POINT (549611.8 6189285)
#> 2 12.00 129 POINT (700990.8 6223807)
Created on 2024-03-20 with reprex v2.1.0
Upvotes: 2