如何在 R 中创建“非常大的整数”的 2 路矩阵?

问题描述 投票:0回答:2

我计划使用 R 包

VeryLargeIntegers
来处理巨大的整数。

我想创建一个由这些大整数组成的新矩阵。最初,矩阵的所有值都等于 0,然后我将用非常大的数字更新它们的值。

我是这样开始的:


# install.packages("VeryLargeIntegers")
library(VeryLargeIntegers)

PI <- matrix(NA, nrow = 30, ncol = 436)

# Doing this with a double `for` loop because the other ways I tried were throwing an error

for(i in 1:30){
    for(j in 1:436){
        PI[i,j] <- as.vli("0")
    }
}

# ALSO RETURNS AN ERROR MESSAGE:
# Error in PI[i, j] <- as.vli("0") :
# número de items para para sustituir no es un múltiplo de la longitud del reemplazo

也尝试过这个:


# install.packages("VeryLargeIntegers")
library(VeryLargeIntegers)

PI <- array(as.vli("0"), dim = c(30,436))

# Does not throw an error, but:

is.vli(PI[4,6]) # FALSE

as.vli(PI[4,6]) # ERROR

所以,我想这很容易,但我什至不知道如何正确构建填充有

vli
对象的 2 路矩阵或数组,以及如何在(显然)创建它时访问其
vli
元素.

我期待您的答复。预先感谢您!

r arrays largenumber
2个回答
1
投票

你真的需要矩阵结构吗?您不能构建仅由 VeryLargeIntegers 列表组成的向量或矩阵。但是你可以用一个向量的展平矩阵来模拟一个矩阵(这是内部完成的)。

function vliMatrix(nRows, nCols) {
  structure(
    vli(nRows*nCols),
    nRows=nRows,
    nCols=nCols
  )
}

function getFromRowCol(x, row, col) {
  nCols <- attr(x, "nCols")
  x[[(row-1)*nCols+cols]]
}

function setToRowCols(x, row, col, value) {
  nCols <- attr(x, "nCols")
  x[[(row-1)*nCols+cols]] <- as.vli(value)
  x
}

a <- vliMatrix(10,10)
a <- setToRowCol(2,3,1256698)
print(getFromRowCol(a,2,3))

0
投票

这种有效:

PI0 <- replicate(30*436, as.vli("0"), simplify = FALSE)
dim(PI0) <- c(30, 436)
PI0[4,6][[1]]
Very Large Integer: 
[1] 0

如果您想更加努力地工作,您可以为此定义自己的 S3 类,并为

[
编写一个方法来提取 VLI ...

我不太确定为什么检索

dim
化对象的元素会返回长度为 1 包含 VLI 而不是原始 VLI 的列表,但也许您可以接受这一点。

© www.soinside.com 2019 - 2024. All rights reserved.