I can try to assign waldo::compare()
to an object:
waldo_diff <- waldo::compare(vec_a, vec_b)
and then what? when I try to do waldo_diff[[1]]
I get:
[1] "`old[8:10]`: \033[90m12\033[39m \033[90m6\033[39m \033[90m18\033[39m \n`new[8:11]`: \033[90m12\033[39m \033[90m6\033[39m \033[90m18\033[39m \033[34m4\033[39m"
and for waldo_diff[[2]]
it's even worse:
Error in waldo_diff[3] : subscript out of bounds
Any idea how I could programmatically extract the outstanding values that appear in the "new" vector but not in the "old"?
As a disclaimer, I didn't know anything about this package until you posted so this is far from an authoritative answer, but you can't easily extract the different values using the compare()
function as it returns an ANSI formatted string ready for pretty printing. Instead the workhorses for vectors seem to be the internal functions ses()
and ses_context()
which return the indices of the differences between the two objects. The difference seems to be that ses_context()
splits the result into a list of non-contiguous differences.
waldo:::ses(vec_a, vec_b)# A tibble: 1 x 5x1 x2 t y1 y2<int> <int> <chr> <int> <int>1 10 10 a 11 11
The results show that there is an addition in the new vector beginning and ending at position 11.
The following simple function is very limited in scope and assumes that only additions in the new vector are of interest:
new_diff_additions <- function(x, y) {res <- waldo:::ses(x, y)res <- res[res$t == "a",] # keep only additionsif (nrow(res) == 0) {return(NULL)} else {Map(function(start, end) {d <- y[start:end]`attributes<-`(d, list(start = start, end = end))},res[["y1"]], res[["y2"]])}}new_diff_additions(vec_a, vec_b)[[1]][1] 4attr(,"start")[1] 11attr(,"end")[1] 11
At least for the simple case of comparing two vectors, you’ll be better offusing diffobj::ses_dat()
(which is from the package that waldo usesunder the hood) directly:
waldo::compare(1:3, 2:4)#> `old`: 1 2 3 #> `new`: 2 3 4diffobj::ses_dat(1:3, 2:4)#> op val id.a id.b#> 1 Delete 1 1 NA#> 2 Match 2 2 NA#> 3 Match 3 3 NA#> 4 Insert 4 NA 3
For completeness, to extract additions you could do e.g.:
extract_additions <- function(x, y) {ses <- diffobj::ses_dat(x, y)y[ses$id.b[ses$op == "Insert"]]}old <- 1:3new <- 2:4extract_additions(old, new)#> [1] 4