Writing a binary file to R

I am invited to write R-output in two binary files, an index file and a master data file. There will be one matrix / block in the index file corresponding to each identifier. I read about writing binary files in R on the Internet, but I'm not sure how to specify a format so that I can achieve this format?

You can also specify a short integer in R? He said he wants the numbers to be short swords (two bytes), and I don't want what that means.

I appreciate any input! Thanks

+4
source share
2 answers

Since you did not indicate the problem very clearly, I made some assumptions in the code example below. Given a list of matrices, it saves them in a .bin file and creates a .idx file with offsets. Then you can load them again based on the index. The 2-byte size you mentioned is not used - it stores the matrix data as 8-byte double or 4-byte integers (but you can change this).

Here's how it is used:

 mtx <- list(matrix(1:12,4), matrix(sin(1:12),4)) saveMatrixList("c:/foo", mtx) loadMatrix("c:/foo", 1) loadMatrix("c:/foo", 2) 

... and here are the functions:

 saveMatrixList <- function(baseName, mtxList) { idxName <- paste(baseName, ".idx", sep="") idxCon <- file(idxName, 'wb') on.exit(close(idxCon)) dataName <- paste(baseName, ".bin", sep="") con <- file(dataName, 'wb') on.exit(close(con)) writeBin(0L, idxCon) for (m in mtxList) { writeBin(dim(m), con) writeBin(typeof(m), con) writeBin(c(m), con) flush(con) offset <- as.integer(seek(con)) cat('offset', offset) writeBin(offset, idxCon) } flush(idxCon) } loadMatrix <- function(baseName = "data", index) { idxName <- paste(baseName, ".idx", sep="") idxCon <- file(idxName, 'rb') on.exit(close(idxCon)) dataName <- paste(baseName, ".bin", sep="") con <- file(dataName, 'rb') on.exit(close(con)) seek(idxCon, (index-1)*4) offset <- readBin(idxCon, 'integer') seek(con, offset) d <- readBin(con, 'integer', 2) type <- readBin(con, 'character', 1) structure(readBin(con, type, prod(d)), dim=d) } 
+3
source

See the help (writeBin), size = 2 defines the distribution for each element (i.e. an integer of two bytes). But if you do not know what this means, you will probably need much more information from your requester.

+1
source

All Articles