[英]How to preserve data format between fread and fwrite in R
I have a data.table field that is a number but stored as a character.我有一个 data.table 字段,它是一个数字,但存储为一个字符。 If I save the data.table using
fwrite
as a text file and read it using fread
, the type of this field changes to integer.如果我使用
fwrite
将 data.table 保存为文本文件并使用fread
读取它,则此字段的类型将更改为 integer。 Is there a way to preserve the original type of the field without having to coerce later?有没有办法保留字段的原始类型而不必稍后强制?
Yes,是的,
Here is a reproducible example:这是一个可重现的示例:
library(data.table)
df <- data.frame(c1 = 1:10, c2 = as.character(11:20))
df <- as.data.table(df)
fwrite(df, "your_address_here", quote = TRUE)
df <- fread("your_address_here", colClasses = c(c2 = "character"))
The trick is to set quote=TRUE
in fwrite()
and to specify the type of the column in fread()
with colClasses
argument, using a named vector.诀窍是在
fwrite()
中设置quote=TRUE
并使用命名向量在fread()
中使用colClasses
参数指定列的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.