如何在R中的二进制文件中替换值?

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

我必须使用(自定义)二进制文件格式。数据对于我的RAM来说太大了,我只需要导入其中的一小部分,进行一些计算并用新值覆盖/替换该部分(因此,我不想导入所有内容,更改特定部分并编写所有内容返回)。

我尝试了seekwriteBin的组合,但这会生成一个小文件,其新值以零开头:

fn <- tempfile()

writeBin(1L:3L, fn, size = 1L)
readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1] 1 2 3

fh <- file(fn, "wb")
isSeekable(fh)
#> [1] TRUE
seek(fh, 1L, origin = "start", rw = "write")
#> [1] 0
# swap the sign of the second value
writeBin(-2L, fh, size = 1L)
close(fh)

readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1]  0 -2

unlink(fn)

使用ab模式附加到文件也无济于事:

fn <- tempfile()

writeBin(1L:3L, fn, size = 1L)
readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1] 1 2 3

fh <- file(fn, "ab")
isSeekable(fh)
#> [1] TRUE
seek(fh, 1L, origin = "start", rw = "write")
#> [1] 3
# swap the sign of the second value
writeBin(-2L, fh, size = 1L)
close(fh)

readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1] 1 2 3

unlink(fn)

我的预期输出为1 -2 3

R中是否有此方法,还是我必须使用C

r binaryfiles seek
1个回答
0
投票

经过一番反复尝试后,我自己找到了解决方案:使用模式"r+b"支持数据替换。

fn <- tempfile()

writeBin(1L:3L, fn, size = 1L)
readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1] 1 2 3

fh <- file(fn, "r+b")
isSeekable(fh)
#> [1] TRUE
seek(fh, 1L, origin = "start", rw = "write")
#> [1] 0
# swap the sign of the second value
writeBin(-2L, fh, size = 1L)
close(fh)

readBin(fn, what = "integer", size = 1L, n = 3L)
#> [1]  1 -2  3

unlink(fn)
© www.soinside.com 2019 - 2024. All rights reserved.