是否可以向量化输出 bigz 对象的函数?

Is it possible to Vectorize functions that output bigz objects?

我怀疑一定有某种方法,例如 gmpfactorialZ 似乎是预矢量化的:

> library(gmp)
> factorialZ(0:9)
Big Integer ('bigz') object of length 10:
 [1] 1      1      2      6      24     120    720    5040   40320  362880

与采用矢量输入并给出矢量输出的基本 R 函数一起使用似乎很舒服

> cumsum(factorialZ(0:9))
Big Integer ('bigz') object of length 10:
 [1] 1      2      4      10     34     154    874    5914   46234  409114

然而,可能是因为强制转换,尝试 Vectorize 输出 bigZ 对象的函数将遇到可怕的失败:

leftFactorial<-function(n)
{
  sum(factorialZ(0:(n-1)))
}
> Vectorize(leftFactorial)(1:10)
  [1] 01 00 00 00 01 00 00 00 01 00 00 00 01 00 00 00 01 00 00 00 01 00 00 00 01 00 00 00 02 00 00 00 01 00 00
 [36] 00 01 00 00 00 01 00 00 00 04 00 00 00 01 00 00 00 01 00 00 00 01 00 00 00 0a 00 00 00 01 00 00 00 01 00
 [71] 00 00 01 00 00 00 22 00 00 00 01 00 00 00 01 00 00 00 01 00 00 00 9a 00 00 00 01 00 00 00 01 00 00 00 01
[106] 00 00 00 6a 03 00 00 01 00 00 00 01 00 00 00 01 00 00 00 1a 17 00 00 01 00 00 00 01 00 00 00 01 00 00 00
[141] 9a b4 00 00 01 00 00 00 01 00 00 00 01 00 00 00 1a 3e 06 00

那么当我们想要Vectorize一个输出bigZ对象的函数时我们应该怎么做呢?

dput 允许可视化 bigZ 对象的内部结构:raw

的向量
> dput(factorialZ(0:9))
structure(as.raw(c(0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 
0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 
0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 
0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x00, 
0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x78, 
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 
0xd0, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 
0x00, 0xb0, 0x13, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 
0x00, 0x00, 0x80, 0x9d, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 
0x00, 0x00, 0x00, 0x80, 0x89, 0x05, 0x00)), class = "bigz")

VectorizeSIMPLIFY = TRUE 结合使用可生成 raw 个对象的简化矢量。

如评论中所述,SIMPLIFY = FALSE 有效,因为它保留了原始 Big Integer 类型:

Vectorize(leftFactorial, SIMPLIFY = FALSE)(1:10)

[[1]]
Big Integer ('bigz') :
[1] 1

[[2]]
Big Integer ('bigz') :
[1] 2

[[3]]
Big Integer ('bigz') :
[1] 4

[[4]]
Big Integer ('bigz') :
[1] 10

[[5]]
Big Integer ('bigz') :
[1] 34

[[6]]
Big Integer ('bigz') :
[1] 154

[[7]]
Big Integer ('bigz') :
[1] 874

[[8]]
Big Integer ('bigz') :
[1] 5914

[[9]]
Big Integer ('bigz') :
[1] 46234

[[10]]
Big Integer ('bigz') :
[1] 409114