Skip to content

Instantly share code, notes, and snippets.

@brodieG
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save brodieG/98c68ab8d076560b2b3f to your computer and use it in GitHub Desktop.

Select an option

Save brodieG/98c68ab8d076560b2b3f to your computer and use it in GitHub Desktop.
Using `alike` with `ensurer`
# Packages
library(devtools)
install_github("smbache/ensurer")
install_github("brodieg/alike")
library(ensurer)
library(alike)
library(magrittr)
set.seed(1)
# Objects to test
iris.tpl <- iris[0, ]
iris.2 <- iris.3 <- iris[sample(seq(len=nrow(iris)), 10), ] # random subset of iris
levels(iris.3$Species) <- c(levels(iris.3$Species), "americana") # add level to iris.3
# Template test 1 (from `ensurer` vignette)
ensure_as_template <- function(x, tpl)
ensure_that(x,
is.data.frame(.),
identical(class(.), class(tpl)),
identical(sapply(., class), sapply(tpl, class)),
identical(sapply(., levels), sapply(tpl, levels))
)
x.1 <- iris.2 %>% ensure_as_template(iris.tpl) # pass
x.2 <- iris.3 %>% ensure_as_template(iris.tpl) # fail
# Template test 2 (alike adaptation)
ensure_as_template2 <- function(x, tpl)
ensure_that(x, alike(tpl, .))
x.3 <- iris.2 %>% ensure_as_template2(iris.tpl) # pass
x.4 <- iris.3 %>% ensure_as_template2(iris.tpl) # fail
alike(iris.tpl, iris.3) # alike tells you why the structure is unequal
# [1] "Mismatch at column `Species`: length mismatch for attribute \"levels\": expected 3, but got 4"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment