Reputation: 69
I'm writing a data table to csv using fwrite
. The function changes the class of one column from character to integer and deleted the starting zeros, which I do not want. So my var2 here is character, and I would like to preserve that through fwrite then fread a subset.
However, what I got was the following:
head(DT)
var1 var2
1 "0012"
2 "0032"
3 "0043"
DT1 <- DT[var1!=2,]
fwrite(DT1,"DT1.csv", row.names=FALSE)
Then:
DT1 <- fread("DT1.csv")
head(DT1)
var1 var2
1 12
3 43
Is there any way I can fix it?
Upvotes: 2
Views: 1098
Reputation: 451
The issue is with fread
rather than fwrite
. So just specify that var2
is a character
class. The default in fread
is sensing that var2
is a numeric
column so just add the following in your call to fread
:
DT1<-fread("DT1.csv", colClasses = list(character=c("var2")))
Let me know if this works for you and good luck!
Upvotes: 2