Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion R/sdFrame.R
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need to double check but I think logical filter should be quite efficient (more efficient than our version with numeric indices) in SQL. So maybe we need to process these directly

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)
}
6 changes: 4 additions & 2 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
Loading