Skip to content

Commit fc72659

Browse files
committed
st_as_sfc.data.frame() handles NAs better
r-spatial/s2#289
1 parent 34d4aba commit fc72659

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

R/sf.R

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,23 +46,26 @@ st_as_sf.data.frame = function(x, ..., agr = NA_agr_, coords, wkt,
4646
else
4747
x$geometry = st_as_sfc(as.character(x[[wkt]]))
4848
} else if (! missing(coords)) {
49-
cc = as.data.frame(lapply(x[coords], as.numeric))
50-
if (na.fail && anyNA(cc))
49+
cc = as.matrix(as.data.frame(lapply(x[coords], as.numeric)))
50+
anyna = anyNA(cc)
51+
if (na.fail && anyna)
5152
stop("missing values in coordinates not allowed")
53+
if (anyna)
54+
cc[apply(cc, 1, anyNA),] = NA_real_
5255
# classdim = getClassDim(rep(0, length(coords)), length(coords), dim, "POINT")
5356
if (is.null(sf_column_name))
5457
sf_column_name = "geometry"
5558
x[[sf_column_name]] = if (nchar(dim) < 4 && ncol(cc) == 4) { # create POLYGONs:
5659
fn = function(x) st_as_sfc(st_bbox(c(xmin = x[[1]], ymin = x[[2]], xmax = x[[3]], ymax = x[[4]])))
57-
do.call(c, apply(as.matrix(cc), 1, fn))
60+
do.call(c, apply(cc, 1, fn))
5861
} else { # points:
59-
structure( points_rcpp(as.matrix(cc), dim),
62+
structure(points_rcpp(cc, dim),
6063
n_empty = 0L, precision = 0, crs = NA_crs_,
6164
bbox = structure(
62-
c(xmin = min(cc[[1]], na.rm = TRUE),
63-
ymin = min(cc[[2]], na.rm = TRUE),
64-
xmax = max(cc[[1]], na.rm = TRUE),
65-
ymax = max(cc[[2]], na.rm = TRUE)), class = "bbox"),
65+
c(xmin = min(cc[,1], na.rm = TRUE),
66+
ymin = min(cc[,2], na.rm = TRUE),
67+
xmax = max(cc[,1], na.rm = TRUE),
68+
ymax = max(cc[,2], na.rm = TRUE)), class = "bbox"),
6669
class = c("sfc_POINT", "sfc" ), names = NULL)
6770
}
6871

0 commit comments

Comments
 (0)