将原始向量存储为数据框中的单个值

Storing a raw vector as a single value in a data frame

我有一些数据需要以二进制格式放入数据框中(作为由原始向量表示的单个条目)。这是一个例子:

#Record identifier
idx <- "identifier"

#The numeric data for a single record
aa <- c(5.99, 999, 5.99, 82.93)

#Convert data to double precision binary format
bin.aa <- writeBin(aa, raw(), endian = "little")

print(bin.aa)
[1] f6 28 5c 8f c2 f5 17 40 00 00 00 00 00 38 8f 40 f6 28 5c 8f c2 f5 17 40 ec 51 b8 1e 85 bb 54 40

到目前为止一切顺利。我有我想要的原始向量。现在我想制作一个包含两列和一行的数据框,其中包含(在第 1 列中)"identifier" 和(在第 2 列中)原始向量 bin.aa。不幸的是,我的尝试没有奏效:

> df <- data.frame(idx, bin.aa)

> head(df)
         idx bin.aa
1 identifier     f6
2 identifier     28
3 identifier     5c
4 identifier     8f
5 identifier     c2
6 identifier     f5

这当然不是我想要的 - 我现在有 32 行,每行包含原始向量中的一个字节。我知道可以做我正在尝试的事情,因为我可以做与我在这里尝试的相反的事情:即我可以使用 readBin() 命令将原始向量读取到单个数据帧条目中。显然我在这里遗漏了一些东西。

你可以试试:

df <- data.frame(idx, I(list(bin.aa)))

这里需要 I 运算符,因为 list(bin.aa) 是一个只有一个元素的列表,默认情况下它在 data.frame 调用中不列出。