Search code examples
rtype-conversiondata.tablefwritefread

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. 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. Is there a way to preserve the original type of the field without having to coerce later?


Solution

  • 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.