diff --git a/R/sdFrame.R b/R/sdFrame.R index 80562df7..71c00d5a 100644 --- a/R/sdFrame.R +++ b/R/sdFrame.R @@ -264,12 +264,30 @@ setMethod("[", c("SpatialDataFrame", "ANY", "ANY"), \(x, i, j, ...) { } else { if (is.numeric(i) && any(i < 0)) stop("negative row-subsetting not supported") + if (is.numeric(i) && anyDuplicated(i) > 0) + warning("duplicated row-subsetting not supported") if (is.logical(i)) i <- seq_len(nrow(x))[i] if (is.character(j)) j <- match(j, names(x)) if (missing(j) || isTRUE(j)) j <- seq_len(ncol(x)) data(x) <- data(x) |> - filter(row_number() %in% i) |> + .pseudo_slice(i) |> select(all_of(j)) } return(x) }) + +# dbplyr doesn't provide a slice method for lazy_tbl, as documented, so we +# implement our own pseudo-slice function. +# If the indices are contiguous, we use dplyr::between(), which is converted to +# the much more efficient SQL BETWEEN operator, otherwise we use %in%, which is +# converted to IN, which gets super slow for large numbers of indices. +.pseudo_slice <- \(d, i) { + i <- sort(unique(i[!is.na(i)])) + if (length(i) == 0L) return(dplyr::filter(d, FALSE)) + lo <- i[1] + hi <- i[length(i)] + if (length(i) == hi - lo + 1) + return(dplyr::filter(d, dplyr::between( + dplyr::row_number(), .env$lo, .env$hi))) + dplyr::filter(d, dplyr::row_number() %in% .env$i) +} diff --git a/R/utils.R b/R/utils.R index ba7dfb8b..fc75d0bd 100644 --- a/R/utils.R +++ b/R/utils.R @@ -39,9 +39,11 @@ # get element 'y' annotated by table 't' y <- element(x, j) # match instances between them - y <- y[match(instances(t), instances(y), nomatch=0)] + m <- match(instances(t), instances(y), nomatch=0) + # avoid copy when nothing to drop + if (identical(m, seq_along(m)) && length(m) == length(y)) next # return matching shape instances - shape(x, j) <- y + shape(x, j) <- y[m] } return(x) }