Search code examples
rsubclassr-s3

Subclass of integer64 staying after logical operation (R)


When I subclass the integer64 object from bit64 and then perform a equality test, the result contains logical data, but is still classed with my class rather than being logical. This doesn't happen with integer for example.

Sample code:

library(bit64)
x = as.integer64(5)
class(x) = c("Foo", "integer64")
x == 5

returns

[1] TRUE
attr(,"class")
[1] "Foo"

Notice that it still has class "Foo"

While if we do the same with integer:

y = as.integer(5)
class(y) = c("Foo", "integer")
y == 5

It returns logical

[1] TRUE

Any idea why is this happening?


Solution

  • Look at the implementation of equals for integer64 variables.

    `==.integer64`
    function (e1, e2) 
    {
        a <- binattr(e1, e2)
        e1 <- as.integer64(e1)
        e2 <- as.integer64(e2)
        ret <- logical(max(length(e1), length(e2)))
        .Call("EQ_integer64", e1, e2, ret)
        a$class <- minusclass(a$class, "integer64")
        setattributes(ret, a)
        ret
    }
    

    The return value is explicitly given a class attribute equal to the class of a, minus the class "integer64".

    binattr, that creates the variable a is a rather odd function that checks that the two inputs are of a compatible size, then returns the attributes of one or the other, depending upon which ones have a dim attribute.