如何在 R 应用中取消类型转换(bit64 示例) [英] How to void type conversion in R's apply (bit64 example)
问题描述
我在一些 R 代码中使用了 bit64 包.我创建了一个向量64 位整数,然后尝试使用 sapply
来迭代这些向量中的整数.下面是一个例子:
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)})
is.integer64(x)
和 print(x)
都给出了不正确的(或至少)意外的答案(错误和不正确的浮点值).我可以通过直接索引向量 c
来规避这一点,但我有两个问题:
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:
- 为什么要进行类型转换?在这种情况下,R 是否使用了一些规则?
- 有什么方法可以避免这种类型转换?
TIA.
推荐答案
这里是lapply
的代码:
function (X, FUN, ...)
{
FUN <- match.fun(FUN)
if (!is.vector(X) || is.object(X))
X <- as.list(X)
.Internal(lapply(X, FUN))
}
现在检查这个:
!is.vector(v)
#TRUE
as.list(v)
#[[1]]
#[1] 4.940656e-324
#
#[[2]]
#[1] 9.881313e-324
#
#[[3]]
#[1] 1.482197e-323
来自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
包 authours 应该考虑为 as.list
编写一个方法.可能值得一个功能请求...
The package authours should consider writing a method for as.list
. Might be worth a feature request ...
这篇关于如何在 R 应用中取消类型转换(bit64 示例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!