在 R 中读取已删除记录的 .DBF 文件

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

我想读取 R 中包含“已删除”行的 .dbf 文件。但是,我不知道如何避免阅读所有记录。我正在使用“foreign”包和函数

read.dbf

根据.dbf文件描述,每条记录都以1字节的“删除”标志开头。如果记录处于活动状态,则该字节的值为空格 (0x20);如果记录已删除,则该字节的值为星号 (0x2A)。

如何使用 R 提取此信息?例如。对于保存为 .dbf 文件的

iris
数据集的小样本:

library(foreign)
dbf.file <- 'iris.dbf'
write.dbf(iris[1:5, ], file=dbf.file)
r flags dbf
1个回答
0
投票

我们可以使用

readBin()
函数将.dbf文件读取为二进制数据。

# read binary data
bin <- readBin(dbf.file, what='raw', n=file.size(dbf.file))

然后,根据.dbf格式描述,我们可以读取导航到每条记录的第一个字节所需的信息。 我使用自定义函数将 .dbf 标头中的适当字节转换为无符号整数。

bin_to_int <- function(bin) {
  if (.Platform$endian == 'big') {
    bin <- rev(bin)
  }
  sum(2^(which(as.logical(rawToBits(bin))) - 1))
}

# number of records
n <- bin_to_int(bin[5:8])
# numer of bytes in the header
header.len <- bin_to_int(bin[9:10])
# numer of bytes in the record
record.len <- bin_to_int(bin[11:12])

有了这些,就可以计算记录的第一个字节是什么,并查看它们是否将记录标记为已删除。

# first bytes of records
record.starts <- header.len + 1 + (seq_len(n)-1) * record.len
is.deleted <- bin[record.starts] == 0x2A
is.deleted
# [1] FALSE FALSE FALSE FALSE FALSE

事实上,没有任何记录被标记为已删除,因此我们至少可以检查字节是否包含

0x20
的预期值:

bin[record.starts]
# [1] 20 20 20 20 20

顺便说一句,从文档中不清楚

read.dbf()
如何处理已删除的记录,因此它很可能会忽略它们,您根本不必处理这个问题。了解这一点会很有趣,所以请在评论中告诉我们。

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