Niklaus Kuehnis
2011-May-25 10:06 UTC
[R] What does "smaller than" comparison do on strings?
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
Duncan Murdoch
2011-May-25 14:35 UTC
[R] What does "smaller than" comparison do on strings?
On 25/05/2011 6:06 AM, Niklaus Kuehnis 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 > FALSESee ?Comparison for help. There are lots of details given there. In summary: your second comparison is of "2" to "10". Since the character "2" sorts later than the character "1", "2" < "10" is FALSE. Duncan Murdoch
Dennis Murphy
2011-May-25 18:33 UTC
[R] What does "smaller than" comparison do on strings?
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. >