Search code examples
rcsvexport-to-csv

R write dataframe column to csv having leading zeroes


I have a table that stores prefixes of different lengths.. snippet of table(ClusterTable)

ClusterTable[ClusterTable$FeatureIndex == "Prefix2",'FeatureIndex', 'FeatureValue')]

   FeatureIndex FeatureValue
80      Prefix2           80
81      Prefix2           81
30      Prefix2           30
70      Prefix2           70
51      Prefix2           51
84      Prefix2           84
01      Prefix2           01
63      Prefix2           63
28      Prefix2           28
26      Prefix2           26
65      Prefix2           65
75      Prefix2           75

and I write to csv file using following:

write.csv(ClusterTable, file = "My_Clusters.csv")

The Feature Value 01 loses it leading zero.

I tried first converting the column to characters

ClusterTable$FeatureValue <- as.character(ClusterTable$FeatureValue)

and also tried to append it to an empty string to convert it to string before writing to file.

ClusterTable$FeatureValue <- paste("",ClusterTable$FeatureValue)

Also, I have in this table prefixes of various lengths, so I cant use simple format specifier of a fixed length. i.e the table also has Value 001(Prefix3),0001(Prefix4),etc. Thanks


Solution

  • When dealing with leading zeros you need to be cautious if exporting to excel. Excel has a tendency to outsmart itself and automatically trim leading zeros. You code is fine otherwise and opening the file in any other text editor should show the zeros.