#### waldo R package for comparing R objects ####
###  Presented to the Cornell R User Group    ###
###  December 3, 2024                         ###
###  Tyler Wilcox <ktw34@cornell.edu>         ###

setwd("~/Documents/r-fragments/")

library(waldo)

data(mtcars)

saveRDS(mtcars, "demo-mtcars-orig.rds")
saveRDS(mtcars, "demo-mtcars-2024-12-03.rds")

str(mtcars)

# Convert `cyl` to factor and
mtcars2 <- within(mtcars, {
    cyl <- factor(cyl, levels = sort(unique(cyl)), ordered = TRUE)
    } )

str(mtcars2)

# drop the 31st observation with highest outlying `hp`
drop_ind <- with(mtcars2, which(hp == max(hp)))

mtcars2 <- mtcars2[-drop_ind, ]

# Use waldo::compare() to check for differences between two objects
resc <- compare(mtcars, mtcars2)

# Checks for differences in values, variable types, attributes,
#   new/removed variables, new/removed rows, ...
resc

# If there was a change, length of the comparison object will be > 0
length(resc)

# If there was a change, length of the comparison object will be > 0
if (length(resc) > 0) {
    # Save new version of object
    saveRDS(mtcars2, "demo-mtcars-change.rds")
}

# Example: Check for differences between two versions of data from collaborator
dat1 <- readRDS("demo-mtcars-orig.rds")
dat2 <- readRDS("demo-mtcars-change.rds")
compare(dat1, dat2)

# No differences!
dat3 <- readRDS("demo-mtcars-2024-12-03.rds")
compare(dat1, dat3)

# To learn more, check out the `waldo` website <https://waldo.r-lib.org>
