Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to void type conversion in R's apply (bit64 example)

Tags:

r

sapply

64-bit

I am using the bit64 package in some R code. I have created a vector of 64 bit integers and then tried to use sapply to iterate over these integers in a vector. Here is an example:

v = c(as.integer64(1), as.integer64(2), as.integer64(3))
sapply(v, function(x){is.integer64(x)})
sapply(v, function(x){print(x)})

Both the is.integer64(x) and print(x) give the incorrect (or at least) unexpected answers (FALSE and incorrect float values). I can circumvent this by directly indexing the vector c but I have two questions:

  1. Why the type conversion? Is their some rule R uses in such a scenario?
  2. Any way one can avoid this type conversion?

TIA.

like image 718
user2051561 Avatar asked Mar 19 '23 23:03

user2051561


1 Answers

Here is the code of lapply:

function (X, FUN, ...) 
{
    FUN <- match.fun(FUN)
    if (!is.vector(X) || is.object(X)) 
        X <- as.list(X)
    .Internal(lapply(X, FUN))
}

Now check this:

!is.vector(v)
#TRUE

as.list(v)
#[[1]]
#[1] 4.940656e-324
#
#[[2]]
#[1] 9.881313e-324
#
#[[3]]
#[1] 1.482197e-323

From help("as.list"):

Attributes may be dropped unless the argument already is a list or expression.

So, either you creaste a list from the beginning or you add the class attributes:

v_list <- lapply(as.list(v), function(x) {
  class(x) <- "integer64"
  x
  })

sapply(v_list, function(x){is.integer64(x)})
#[1] TRUE TRUE TRUE

The package authours should consider writing a method for as.list. Might be worth a feature request ...

like image 63
Roland Avatar answered Apr 02 '23 10:04

Roland