Reputation: 675
I am converting a column that has characters such as 000024, 000120 etc to integers.
My code is as below
df$colname <- as.integer(df$colname)
But this removes the leading zeroes and I see result as 24, 120. Is there any way I can prevent it?
Upvotes: 0
Views: 730
Reputation: 206616
Integers don't have a fixed number of leading zeros (or I guess you could say they have infinitely many leading zeros) so computers don't track those if the values as numeric. It's only when displaying them, or turning them into a string that you add a certain number of zeros. When you need them to be pretty, you can add zeros with functions like sprintf("%06d", c(12, 120))
but those return strings in the end (and they assume all values will use the same number of digits).
Upvotes: 3