问题
Suppose I have the following sf
data frame:
library(sf)
nrows <- 10
geometry = st_sfc(lapply(1:nrows, function(x) st_geometrycollection()))
df <- st_sf(id = 1:nrows, geometry = geometry)
And I also have the following list:
mylist = list('2'=st_point(c(-73,42)), '3'=NA)
I want to replace the geometry from the second observation with the point in the list. I had thought about doing the following:
st_geometry(df[names(mylist),]) <- st_sfc(mylist)
But this throws an error:
"Error in vapply(lst, class, rep(NA_character_, 3)) : values must be length 3, but FUN(X[[2]]) result is length 1"
I found the following workaround by first eliminating the NA values:
condition <- mylist[!is.na(mylist)]
st_geometry(df[names(condition),]) <- st_sfc(condition)
Is there a better way to do this? Can I force the NA elements in mylist
to be empty points?
回答1:
That's not working because in.
mylist = list('2'=st_point(c(-73,42)), '3'= NA)
3
is not a POINT but a logical, which (probably) can not be "forced" in any way into a sf
object.
You can circumvent this by substituting your the NA elements of mylyst
to empty POINTS beforehand. For example:
mylist[[which(is.na(mylist))]] <- st_point()
st_geometry(df[names(mylist),]) <- st_sfc(mylist)
, giving:
> df
Simple feature collection with 10 features and 1 field (with 10 geometries empty)
geometry type: GEOMETRY
dimension: XY
bbox: xmin: -73 ymin: 42 xmax: -73 ymax: 42
epsg (SRID): NA
proj4string: NA
id geometry
1 1 GEOMETRYCOLLECTION EMPTY
2 2 POINT (-73 42)
3 3 POINT EMPTY
4 4 GEOMETRYCOLLECTION EMPTY
5 5 GEOMETRYCOLLECTION EMPTY
6 6 GEOMETRYCOLLECTION EMPTY
7 7 GEOMETRYCOLLECTION EMPTY
8 8 GEOMETRYCOLLECTION EMPTY
9 9 GEOMETRYCOLLECTION EMPTY
10 10 GEOMETRYCOLLECTION EMPTY
HTH.
来源:https://stackoverflow.com/questions/46385301/replace-geometries-from-a-list-in-sf