user3437212
user3437212

Reputation: 675

How to convert char to int in R retaining leading zeroes

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

Answers (1)

MrFlick
MrFlick

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

Related Questions