Create a reproducible example:
> p = st_sf(a=3, geometry = st_sfc(st_point(1:2)))
> p = rbind(p,p,p,p,p)
> p$s_id = c(0,0,1,0,0)
> p
Simple feature collection with 5 features and 2 fields
geometry type: POINT
dimension: XY
bbox: xmin: 1 ymin: 2 xmax: 1 ymax: 2
epsg (SRID): NA
proj4string: NA
a geometry s_id
1 3 POINT(1 2) 0
2 3 POINT(1 2) 0
3 3 POINT(1 2) 1
4 3 POINT(1 2) 0
5 3 POINT(1 2) 0
Then its just a conditional replacement into the geometry
column:
> p$geometry[p$s_id==0]=new_point
> p
Simple feature collection with 5 features and 2 fields
geometry type: POINT
dimension: XY
bbox: xmin: 1 ymin: 2 xmax: 1 ymax: 2
epsg (SRID): NA
proj4string: NA
a geometry s_id
1 3 POINT(1433173.30406075 -182... 0
2 3 POINT(1433173.30406075 -182... 0
3 3 POINT(1 2) 1
4 3 POINT(1433173.30406075 -182... 0
5 3 POINT(1433173.30406075 -182... 0
Oops I've replaced s_id==0
lines (demonstrating how you can replace multiple geometries). Replace with s_id==1
for your use!
The problem in your example is the ifelse
is returning a plain list. Wrap it in st_sfc
and your mutate works..
> p = rbind(p,p,p,p,p)
> p$s_id=c(0,0,1,0,0)
> p
Simple feature collection with 5 features and 2 fields
geometry type: POINT
dimension: XY
bbox: xmin: 1 ymin: 2 xmax: 1 ymax: 2
epsg (SRID): NA
proj4string: NA
a geometry s_id
1 3 POINT(1 2) 0
2 3 POINT(1 2) 0
3 3 POINT(1 2) 1
4 3 POINT(1 2) 0
5 3 POINT(1 2) 0
> pm = p %>% mutate(geometry = st_sfc(ifelse(s_id == 1, st_geometry(new_point), geometry)))
> pm
Simple feature collection with 5 features and 2 fields
geometry type: POINT
dimension: XY
bbox: xmin: 1 ymin: -1824335 xmax: 1433173 ymax: 2
epsg (SRID): NA
proj4string: NA
a s_id geometry
1 3 0 POINT(1 2)
2 3 0 POINT(1 2)
3 3 1 POINT(1433173.30406075 -182...
4 3 0 POINT(1 2)
5 3 0 POINT(1 2)
allpoints$geometry[allpoints$sid %in% 'id1'] <- new_point
works as an overwrite, butallpoints[allpoints$sid %in% 'id1', allpoints$geometry] <- new_point
doesn't (because list-column??) – obrl_soil Jun 21 '17 at 6:53ifelse(p$s_id == 1, st_geometry(new_point), p$geometry)
and you'll see the spatialness is dropped byifelse
. See my additional edit for tidyverse solution. – Spacedman Jun 21 '17 at 6:59