Mark Miller
Mark Miller

Reputation: 13123

adding or retaining leading zeros without converting to character format

Is it possible to add or retain one or more leading zeros to a number without the result being converted to character? Every solution I have found for adding leading zeros returns a character string, including: paste, formatC, format, and sprintf.

For example, can x be 0123 or 00123, etc., instead of 123 and still be numeric?

x <- 0123

EDIT

It is not essential. I was just playing around with the following code and the last two lines gave the wrong answer. I just thought maybe if I could have leading zeros with numeric format obtaining the correct answer would be easier.

a7   = c(1,1,1,0); b7=c(0,1,1,1);  # 4
a77  = '1110'    ; b77='0111'   ;  # 4
a777 =  1110     ; b777=0111    ;  # 4

length(b7[(b7 %in% intersect(a7,b7))])

R - count matches between characters of one string and another, no replacement

keyword <- unlist(strsplit(a77, ''))
text    <- unlist(strsplit(b77, ''))
sum(!is.na(pmatch(keyword, text)))

ab7 <- read.fwf(file = textConnection(as.character(rbind(a777, b777))), widths = c(1,1,1,1), colClasses = rep("character", 2))
length(ab7[2,][(ab7[2,] %in% intersect(ab7[1,],ab7[2,]))])

Upvotes: 2

Views: 853

Answers (2)

Greg Snow
Greg Snow

Reputation: 49680

You could always create your own class of objects that has one slot for the value of the number (but if it is stored as numeric then what we see as 123 will actually be stored as as a binary value, something like 01111011 (though probably with more leading 0's)) and another slot or attribute for either the number of leading 0's or the number of significant digits. Then you can write methods for what to do with the number (and what effect that will have on the leading 0's, sig digits, etc.).

The print method could then make sure to print it with the leading zeros while keeping the internal value as a number.

But this seems a bit overkill in most cases (though I know that some fields make a big deal about indicating number of significant digits so that leading 0's could be important). It may be simpler to use the conversion to character methods that you already know about, but just do the printing in a way that does not look obviously like a number, see the cat and print functions for the options.

Upvotes: 6

Carl Witthoft
Carl Witthoft

Reputation: 21532

You are not thinking correctly about what a "number" is. Programming languages store an internal representation which retains full precision to the machine limit. You are apparently concerned with what gets printed to your screen or console. By definition, those number characters are string elements, which is to say, a couple bytes are processed by the ASCII decoder (or equivalent) to determine what to draw on the screen. What x "is," to draw happily on Presidential Testimony, depends on your definition of what "is" is.

Upvotes: 8

Related Questions