How to create a 2-way matrix of "very large integers" in R?

60 Views Asked by At

I am planning to use the R package VeryLargeIntegers to handle gigantic integers.

I want to create a new matrix of those large integers. Initially, all the values of the matrix will be equal to 0, and then I'll be updating their values with really large numbers.

I was starting by this:


# 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

Also tried this:


# 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

So, I guess this is easy, but I don't even know how to properly build a 2-way matrix or array populated with vli objects, and how to access its vli elements when it is (apparently) created.

I look forward to your answers. Thank you in advance!

2

There are 2 best solutions below

0
Billy34 On

Do you really need a matrix structure ? You cannot build vectors or matrices of VeryLargeIntegers only lists of. But you can simulate a matrix with a flattened matrix which is a vector (this is what is done internally).

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))
1
Ben Bolker On

This kind of works:

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

If you wanted to work a bit harder you could probably define your own S3 class for this and write a method for [ that extracted the VLI ...

I'm not quite sure why retrieving an element of the dim-ified object returns a list of length 1 containing a VLI rather than a raw VLI, but maybe you can live with that.