[R] What does "smaller than" comparison do on strings?

Dennis Murphy djmuser at gmail.com
Wed May 25 20:33:36 CEST 2011


Hi:

Here are two alternatives that do work as you expect; sprintf() is your friend:

> sprintf("%2d", 1:12)
 [1] " 1" " 2" " 3" " 4" " 5" " 6" " 7" " 8" " 9" "10" "11" "12"
> sprintf("%02d", 1:12)
 [1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12"
> sprintf("%2d", 1:12) < 10
 [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE
> sprintf("%02d", 1:12) < 10
 [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE

A leading space or leading 0 on the digits 1-9 'fixes' the problem for
the reason Duncan mentioned.

HTH,
Dennis

On Wed, May 25, 2011 at 3:06 AM, Niklaus Kuehnis
<kuehnik_0505 at gmx-topmail.de> wrote:
> What's the logic behind the following, and where can I find any
> documentation about it? In particular, why are 2:9 - as characters - not
> regarded as being smaller than 10?
>
> # R-Code:
> a <- as.character(1:12)
>
> a < 10
> #  [1]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> FALSE
>
> Thanks in advance!
>
> Niklaus
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list