如何反序列化已解压的R Eventlog对象?
问题分析与解决
你的代码核心问题出在读取解压后的序列化数据时未读全内容,以及反序列化的步骤错误,以下是具体修正方案:
错误点拆解
- 读取时使用
file.info("event_log.RDS.gz")$size作为readBin的n参数,这是压缩文件的大小,解压后的实际数据量远大于此,导致数据读取不完整。 - 将
rawConnection直接转成字符的操作错误,无法正确还原序列化内容。
修正方案一:修复原有代码逻辑
library(eventdataR) data("patients") # 序列化(保持原ascii设置) serialized_eventlog <- rawToChar(serialize(object = patients, connection = NULL, ascii = TRUE)) # 写入压缩文件(原逻辑可保留) compressed_con <- gzcon(file("event_log.RDS.gz", "wb")) writeBin(serialized_eventlog, compressed_con) close(compressed_con) # 读取解压后的内容(关键修正) decompressed_con <- gzcon(file("event_log.RDS.gz", "rb")) # 读取全部字符内容,无需指定n(readBin会自动读取到末尾) decompressed_serialized_eventlog <- readBin(decompressed_con, character(), n = 1e6) close(decompressed_con) # 反序列化(直接将字符转raw后反序列化) deserialized_eventlog <- unserialize(charToRaw(decompressed_serialized_eventlog)) # 验证结果 str(deserialized_eventlog)
修正方案二:更简洁的序列化/反序列化流程
直接将序列化操作与压缩连接绑定,省去中间字符转换步骤,更高效且不易出错:
library(eventdataR) data("patients") # 直接序列化到压缩连接 con <- gzcon(file("event_log_compact.RDS.gz", "wb")) serialize(patients, con, ascii = TRUE) close(con) # 直接从压缩连接反序列化 con <- gzcon(file("event_log_compact.RDS.gz", "rb")) deserialized_patients <- unserialize(con) close(con) # 验证结果 str(deserialized_patients)
额外说明
- 若不需要ASCII格式(跨平台兼容性要求不高时),可以去掉
ascii = TRUE,使用二进制序列化,速度更快、文件更小。 - 也可以使用
saveRDS配合gzfile直接实现压缩存储,代码更简洁:# 写入压缩RDS saveRDS(patients, gzfile("patients.rds.gz")) # 读取 patients_restore <- readRDS(gzfile("patients.rds.gz"))
内容的提问来源于stack exchange,提问作者Dr.B
相关产品推荐
相关产品推荐

