Skip to content

Commit

Permalink
Merge pull request #167 from dieghernan/pivotnum
Browse files Browse the repository at this point in the history
Soften checks on mixed types
  • Loading branch information
dieghernan authored Jan 28, 2025
2 parents d53e0f4 + 152f182 commit 6ddfdfd
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@
- `scale_*_cross_blended_tint_c` and `scale_*_cross_blended_tint_b`.
- `scale_*_hypso_tint_c` and `scale_*_hypso_tint_b`.
- `scale_*_grass_c` and `scale_*_grass_b`.
- Now `geom_spatraster()` (and overall pivoting of `SpatRaster` is less strict
with different layer classes: if several layers can be defined as numeric
(i.e. `double`, `integer` and `numeric`) the pivoting (and therefore the
plot) can be performed. This is consistent with `tidyr::pivot_longer()`
behaviour (<https://stackoverflow.com/questions/79292989>).

# tidyterra 0.6.2

Expand Down
4 changes: 4 additions & 0 deletions R/geom_spatraster.R
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,9 @@ check_mixed_cols <- function(r, fn = "tidyterra::geom_spat*") {
todf <- terra::as.data.frame(r[1], xy = FALSE)
col_classes <- unlist(lapply(todf, class))

# Double and integer treated both as numeric, no warning
col_classes <- gsub("integer|numeric|double", "numeric", col_classes)

# If all the same class then do nothing
if (length(unique(col_classes)) == 1) {
# If is factor use combineLevels (terra >= 1.8-10)
Expand All @@ -441,6 +444,7 @@ check_mixed_cols <- function(r, fn = "tidyterra::geom_spat*") {
}

# If not, select the first class

final <- col_classes[1]

# Work with indexes
Expand Down
14 changes: 14 additions & 0 deletions tests/testthat/test-fortify-Spat.R
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,20 @@ test_that("Fortify SpatRasters pivot", {
expect_snapshot(aa <- fortify(fort2, pivot = TRUE))

expect_identical(unique(aa$lyr), names(back))

# No complain in double and integer (treated all as numeric)
# https://stackoverflow.com/questions/79292989

m <- matrix(c(1:24, NA), nrow = 5, ncol = 5)
n <- matrix(rep(5, time = 25), nrow = 5, ncol = 5)

db_int <- terra::rast(c(A = terra::rast(m), B = terra::rast(n)))
expect_identical(terra::is.int(db_int), c(TRUE, FALSE))
expect_silent(db_int_f <- fortify(db_int, pivot = TRUE))

expect_equal(nrow(db_int_f), terra::ncell(db_int) * terra::nlyr(db_int))
expect_identical(unique(db_int_f$lyr), names(db_int))

# What about with no CRS?

r_no <- r
Expand Down

0 comments on commit 6ddfdfd

Please sign in to comment.