Skip to content

Commit

Permalink
Merge pull request #15 from EvolEcolGroup/dev
Browse files Browse the repository at this point in the history
handle X and Y in recipe better
  • Loading branch information
dramanica authored Sep 27, 2023
2 parents a7e6c5d + b7d45d4 commit f8c190c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
18 changes: 13 additions & 5 deletions R/recipe_sf.R
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,19 @@

recipe.sf <- function (x, ...) {
# we should check that all coordinates are points
if (any (c("X","Y") %in% names(x))){
x <- x %>% dplyr::rename(!!"X_orig" := !!"X", !!"Y_orig" := !!"Y")
} # or do we just throw an error and say that X and Y are restricted???

x<-x %>% dplyr::bind_cols(sf::st_coordinates(x)) %>% sf::st_drop_geometry()
# browser()
if (all(c("X", "Y") %in% names(x))) {
if (all(sf::st_drop_geometry(x[, c("X", "Y")]) == sf::st_coordinates(x))) {
x<-x %>% sf::st_drop_geometry()
} else {
stop("sf object `x` contains `X` and `Y` coordinates that do not match the sf point geometry")
}
} else {
x<-x %>% dplyr::bind_cols(sf::st_coordinates(x)) %>% sf::st_drop_geometry()
}



rec <- recipe(x, ...) %>%
update_role(dplyr::any_of(c("X","Y")),new_role="coords")
class(rec) <- c("spatial_recipe", class(rec))
Expand Down
15 changes: 10 additions & 5 deletions tests/testthat/test_recipe_sf.R
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
library(sf)
test_that("sdm_spec_gam", {
test_that("sdm_recipe_sf", {
lacerta_thin <- readRDS(system.file("extdata/lacerta_climate_sf.RDS",
package="tidysdm"))
lacerta_rec <- recipe(lacerta_thin, formula=class~.)
Expand All @@ -10,10 +10,15 @@ test_that("sdm_spec_gam", {
formula=class~.),
"x should be an `sf` object")
lacerta_xy <- lacerta_thin %>% dplyr::mutate(X=1,Y=2)
# recoding old X and Y variable
lacerta_rec_xy <- recipe(lacerta_xy, formula=class~.)
expect_true (all(c("X_orig","Y_orig") %in% lacerta_rec_xy$term_info$variable))
expect_false (all(c("X_orig","Y_orig") %in% lacerta_rec$term_info$variable))
# deal with X and Y coordinates
expect_error(recipe(lacerta_xy, formula=class~.),
"sf object")
lacerta_xy <- lacerta_thin %>% dplyr::bind_cols(sf::st_coordinates(lacerta_thin))
lacerta_xy_rec <- recipe(lacerta_xy, formula=class~.)
expect_true(identical(lacerta_xy_rec,lacerta_rec))
lacerta_xy$X[3]<-190
expect_error(recipe(lacerta_xy, formula=class~.),
"sf object")
#check prep methods
lacerta_rec_prep <- prep(lacerta_rec)
expect_true (recipes::fully_trained(lacerta_rec_prep))
Expand Down

0 comments on commit f8c190c

Please sign in to comment.