【问题标题】:Write binary file in R在R中写入二进制文件
【发布时间】:2011-10-22 19:27:03
【问题描述】:

我被要求将 R 输出写入两个二进制文件,一个索引文件和一个主数据文件。索引文件中的每个 id 都会对应一个矩阵/块。我在网上读到过用 R 写二进制文件,但不知道如何指定格式才能实现这种格式?

另外,我们可以在 R 中指定短整数吗?他说他希望数字是短整数(两个字节),我不想要这意味着什么。

感谢您的任何意见!谢谢

【问题讨论】:

  • 在 StackOverflow 上使用 [r] binary file 快速搜索会发现以下非常相似的问题:stackoverflow.com/q/1635278/602276
  • 正如@mdsummer 所写,您可以指定如何写入大小为2 的整数,但您的问题陈述非常模糊。矩阵数据是整数还是 ids 整数?或者也许 id 是字符串?
  • 欢迎来到 StackOverflow!如果此处的答案之一是您需要的,则应将其标记为答案。否则更新您的问题以澄清您的需求。您还应该投票赞成您喜欢的答案(和问题)。只需点击左上角的分数!

标签: r binary integer byte binaryfiles


【解决方案1】:

由于你没有很清楚地说明问题,我在下面的示例代码中做了一些假设。给定一个矩阵列表,它将它们保存到一个.bin 文件并创建一个带有偏移量的.idx 文件。然后,您可以在给定索引的情况下再次加载它们。您提到的 2 字节大小未使用 - 它将矩阵数据保存为 8 字节双精度或 4 字节整数(但您可以更改它)。

它的使用方法如下:

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

loadMatrix("c:/foo", 1)
loadMatrix("c:/foo", 2)

...这里是函数:

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)
}

【讨论】:

    【解决方案2】:

    参见 help(writeBin),size = 2 定义了对每个元素的分配(即一个两字节整数)。但是,如果您不知道这意味着什么,您可能需要请求者提供更多信息。

    【讨论】:

      猜你喜欢
      • 2017-06-30
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 2013-05-09
      • 2015-02-22
      相关资源
      最近更新 更多