diff --git a/R/utils.R b/R/utils.R index ba7dfb8b..22846749 100644 --- a/R/utils.R +++ b/R/utils.R @@ -38,8 +38,17 @@ if (layer(x, j) != "shapes") next # get element 'y' annotated by table 't' y <- element(x, j) - # match instances between them - y <- y[match(instances(t), instances(y), nomatch=0)] + # nothing to drop if 't' has all instances of 'y' + # (e.g. if 't' is numbered by row position) + if (!all(instances(y) %in% instances(t))) { + # match instances between them; if 'y' has no instance + # key, use its column named after the table's, if any + ik <- instance_key(t) + ky <- tryCatch(instance_key(y), error=\(e) NULL) + ok <- is.null(ky) && ik %in% names(y) + is <- if (ok) y[[ik]] else instances(y) + y <- y[match(instances(t), is, nomatch=0)] + } # return matching shape instances shape(x, j) <- y } diff --git a/inst/NEWS b/inst/NEWS index 6e2ccb96..09b5bc09 100644 --- a/inst/NEWS +++ b/inst/NEWS @@ -1,5 +1,7 @@ changes in devel +- fixed shapes being dropped when adding a table: shapes without a key are + matched on their column named after the table's 'instance_key', if any (#252) - added 'version()' to retrieve format versions of SpatialData elements (#288) - Now using `backed=TRUE` argument internally in `anndataR::read_zarr` to read `table` elements as Zarr-backed SingleCellExperiment objects (#290) diff --git a/tests/testthat/test-sync.R b/tests/testthat/test-sync.R index bdfc0f16..127cbfdd 100644 --- a/tests/testthat/test-sync.R +++ b/tests/testthat/test-sync.R @@ -45,3 +45,42 @@ test_that(".sync_tables_on_crop,shape", { expect_equal(ncol(se), 1) # right instances expect_identical(region(se), i) # regions untouched }) + +test_that(".sync_shapes_on_drop", { + i <- shapeNames(sd)[1] + + # give shapes ids from 0, in a column + # named after the table's instance key + e <- mutate(element(sd, i), instance_id=row_number()-1) + n <- length(id <- e$instance_id) + shape(sd, i) <- e + + # mock shape annotation; unlike 'setTable()', + # 'table<-' doesn't set the shapes' key + se <- table(sd)[, seq_len(n)] + regions(se) <- i + instances(se) <- id + + # all shapes are kept + x <- sd; table(x, "se") <- se + expect_identical(element(x, i)$instance_id, id) + + # dropping an observation drops its shape + table(x, "se") <- se[, -1] + expect_identical(element(x, i)$instance_id, id[-1]) + + # a table numbered by row position keeps + # all shapes, although they have an 'instance_id' + instances(se) <- seq_len(n) + x <- sd; table(x, "se") <- se + expect_identical(element(x, i)$instance_id, id) + + # shapes with their own instance key are + # matched on it, not on 'instance_id' + e <- mutate(e, a=instance_id+100) + instance_key(meta(e)) <- "a" + shape(sd, i) <- e + instances(se) <- e$a + x <- sd; table(x, "se") <- se[, 1:2] + expect_identical(element(x, i)$a, e$a[1:2]) +})