Reputation: 13
Let's say I have some vectors:
> a=c(1:5, NA, 7:10)
> b=a
> a
[1] 1 2 3 4 5 NA 7 8 9 10
> b
[1] 1 2 3 4 5 NA 7 8 9 10
If I use the stopifnot() function, then this will generate the error, because of the NA values, but I would like it not to do so...
> stopifnot(a==b)
Error: a == b are not all TRUE
> a==b
[1] TRUE TRUE TRUE TRUE TRUE NA TRUE TRUE TRUE TRUE
>
I could modify my vectors so that I get the behaviour that I want
> a[is.na(a)]="missing"
> b[is.na(b)]="missing"
> a
[1] "1" "2" "3" "4" "5" "missing" "7" "8" "9" "10"
> b
[1] "1" "2" "3" "4" "5" "missing" "7" "8" "9" "10"
> stopifnot(a==b)
> a==b
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
>
But then I have the hassle of having to reset the "missing" values back to NA
> a[a=="missing"]=NA
> b[b=="missing"]=NA
> a
[1] "1" "2" "3" "4" "5" NA "7" "8" "9" "10"
> b
[1] "1" "2" "3" "4" "5" NA "7" "8" "9" "10"
And I have to reconvert the type, which is annoying
> typeof(a)
[1] "character"
> typeof(b)
[1] "character"
> a=as.numeric(a)
> b=as.numeric(b)
> a
[1] 1 2 3 4 5 NA 7 8 9 10
> b
[1] 1 2 3 4 5 NA 7 8 9 10
Is there a better way?
Upvotes: 0
Views: 206
Reputation: 132706
Typically you would use identical
or, in particular for floating point numbers, the less strict all.equal
:
a <- c(1:5, NA, 7:10)
b <- a
stopifnot(isTRUE(all.equal(a, b)))
#no output
Upvotes: 1