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

半腔热情 提交于 2019-12-01 21:59:21

问题


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.


回答1:


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 ...



来源:https://stackoverflow.com/questions/22906843/how-to-void-type-conversion-in-rs-apply-bit64-example

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!