Taken from github. I am trying to replace an error in geocoding with the correct coordinates. Any workarounds or suggestions? Thanks! Other submissions failed when I tried them.
library(sf)
#> Warning: package 'sf' was built under R version 4.3.3
#> Linking to GEOS 3.11.2, GDAL 3.8.2, PROJ 9.3.1; sf_use_s2() is TRUE
library(dplyr)
#> Warning: package 'dplyr' was built under R version 4.3.3
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df <- data.frame(
name = c("Point A", "Point B", "Point C"),
lon = c(-71.5429688, -75.234375, -63.1054688),
lat = c(-33.1375512, -13.7527247, 5.6159858)
)
sf <- st_as_sf(df, coords = c("lon", "lat"), crs = 4326)
sf %>%
mutate(
geometry = case_when(
name == "Point A" ~ st_cast(
st_sfc(st_point(c(5, 6))),
"GEOMETRY"
),
TRUE ~ st_cast(geometry, "GEOMETRY")
)
)
#> Error in `stopifnot()`:
#> ℹ In argument: `geometry = case_when(...)`.
#> Caused by error in `case_when()`:
#> ! Can't combine `..1 (right)` <sfc_GEOMETRY> and `..2 (right)` <sfc_GEOMETRY>.
#> ✖ Some attributes are incompatible.
#> ℹ The author of the class should implement vctrs methods.
#> ℹ See <https://vctrs.r-lib.org/reference/faq-error-incompatible-attributes.html>.
Created on 2024-09-06 with reprex v2.1.1
2
I think your current strategy was throwing an error because the crs was not the same between the resulting geometries, defining the crs fixes the problem.
sf_mod <- sf %>%
mutate(geometry = case_when(
name == "Point A" ~ st_cast(st_sfc(st_point(c(
5, 6
)), crs = 4326), "GEOMETRY"),
TRUE ~ st_cast(geometry, "GEOMETRY")
))
Per Chris’s comment above though you don’t need to be casting each piece to get the result you want, so this also works and might be easier to to adapt to when you have a longer list of geometries you need to fix.
sf_mod <- sf %>%
mutate(geometry = case_when(
name == "Point A" ~ st_as_sfc("POINT (5 6)", crs = 4326),
TRUE ~ geometry
))
Applying it to across many cases ends up being a bit complicated by how “sticky” the geometry columns are so had to end up converting it to a data frame and then re-converting to sf.
sf_fixes <- data.frame(
name = c("Point A", "Point B"),
x = c(5, -65),
y = c(6, -6)
) %>%
mutate(GEOM_FIX = paste0("POINT (", x, " ", y, ")"))
sf_mod2 <- sf %>%
left_join(sf_fixes) %>%
data.frame() %>%
mutate(geometry = st_as_text(geometry)) %>%
mutate(geometry = case_when(!is.na(GEOM_FIX) ~ GEOM_FIX, TRUE ~ geometry)) %>%
mutate(geometry = st_as_sfc(geometry, crs = 4326)) %>%
st_as_sf()
There are probably other ways to achieve the same thing using map functions, or breaking up/re-constructing the geometry column using st_coordinates() to avoid having make the text string that describes the points for st_as_sfc()
2
Linked code snippet is a reprex for a rather specific issue, it’s not something you should aim for or need to worry about if you just want to update some spcific coordinates in your sf
object.
As Chris pointed out in comments, updating values through subsetting is often all you need, here with a logical vector (sf$name == "Point A"
):
library(sf)
#> Linking to GEOS 3.12.1, GDAL 3.8.4, PROJ 9.3.1; sf_use_s2() is TRUE
library(dplyr, warn.conflicts = FALSE)
sf$geometry[sf$name == "Point A"] <- st_as_sfc("POINT (5 6)")
sf
#> Simple feature collection with 3 features and 1 field
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: -75.23438 ymin: -13.75272 xmax: 5 ymax: 6
#> Geodetic CRS: WGS 84
#> # A tibble: 3 × 2
#> name geometry
#> * <chr> <POINT [°]>
#> 1 Point A (5 6)
#> 2 Point B (-75.23438 -13.75272)
#> 3 Point C (-63.10547 5.615986)
# Or directly fiddle with coordinate values in sfc / sfg:
sf$geometry[sf$name == "Point A"][[1]][1:2] <- c(50, 60)
sf
#> Simple feature collection with 3 features and 1 field
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: -75.23438 ymin: -13.75272 xmax: 50 ymax: 60
#> Geodetic CRS: WGS 84
#> # A tibble: 3 × 2
#> name geometry
#> * <chr> <POINT [°]>
#> 1 Point A (50 60)
#> 2 Point B (-75.23438 -13.75272)
#> 3 Point C (-63.10547 5.615986)
If you need to adjust more coordinates, perhaps from another frame / CSV file, dplyr
method for this would be rows_update()
, unfortuantely it is not (yet?) implemented in sf
(somewhat related discussion ), but crude attempt for sf
objects might look something like this:
rows_update_sf <- function(x, y, ...){
stopifnot(st_crs(x) == st_crs(y))
geom_col <- attr(x, "sf_column")
# drop sf class (while keeping tbl_df) to make dplyr::rows_update() happy
class(x) <- setdiff(class(x), "sf")
class(y) <- setdiff(class(y), "sf")
df_upd <- rows_update(x, y, ...)
# make sure we return an object with updated bbox
df_upd[[geom_col]] <- st_sfc(df_upd[[geom_col]], recompute_bbox = TRUE)
st_sf(df_upd)
}
rows_update_sf(sf, coord_update)
#> Matching, by = "name"
#> Simple feature collection with 3 features and 1 field
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: -63.10547 ymin: 5.615986 xmax: 33 ymax: 44
#> Geodetic CRS: WGS 84
#> # A tibble: 3 × 2
#> name geometry
#> <chr> <POINT [°]>
#> 1 Point A (11 22)
#> 2 Point B (33 44)
#> 3 Point C (-63.10547 5.615986)
Example data:
# use both tibble and data.frame to illustrate how rows_update_sf()
# respects frame class, but sets output according to x
sf <-
tibble(
name = c("Point A", "Point B", "Point C"),
lon = c(-71.5429688, -75.234375, -63.1054688),
lat = c(-33.1375512, -13.7527247, 5.6159858)
) |>
st_as_sf(coords = c("lon", "lat"), crs = 4326)
sf
#> Simple feature collection with 3 features and 1 field
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: -75.23438 ymin: -33.13755 xmax: -63.10547 ymax: 5.615986
#> Geodetic CRS: WGS 84
#> # A tibble: 3 × 2
#> name geometry
#> * <chr> <POINT [°]>
#> 1 Point A (-71.54297 -33.13755)
#> 2 Point B (-75.23438 -13.75272)
#> 3 Point C (-63.10547 5.615986)
csv_txt =
"name,lon,lat
Point A,11,22
Point B,33,44"
coord_update <-
read.csv(text = csv_txt) |>
st_as_sf(coords = c("lon", "lat"), crs = 4326)
coord_update
#> Simple feature collection with 2 features and 1 field
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 11 ymin: 22 xmax: 33 ymax: 44
#> Geodetic CRS: WGS 84
#> name geometry
#> 1 Point A POINT (11 22)
#> 2 Point B POINT (33 44)