[R] ordering of alphanumeric strings

Tony Plate tplate at blackmesacapital.com
Thu Jul 10 23:03:37 CEST 2003


I would be very surprised if any version of R ever ordered strings in the 
manner you want.  R has no way of knowing that some digit strings nestled 
amongst alphabetic characters should be treated as numbers.

To achieve what you want you need to parse the strings yourself, e.g.:
 > x <- c("ABC 10", "ABC 2")
 > x1 <- do.call("rbind", strsplit(x, " "))
 > x2 <- list(x1[,1], as.numeric(as.character(x1[,2])))
 > do.call("order", x2)
[1] 2 1
 >

The above will only work if each element of 'x' has the same number of 
spaces in it (i.e., splitting on a space breaks each element into the same 
number of components).

hope this helps,

Tony Plate

At Thursday 04:37 PM 7/10/2003 -0400, kschlauc wrote:
>Can someone tell me which version of R began to order
>alpha-numeric strings in this manner:
>"ABC 10" < "ABC 2"
>rather than
>"ABC 2" < "ABC 10" ?
>
>And, is there a way to force "ABC 2"
>to be ordered as a value less than "ABC 10"?
>
>thank you,
>Karen
>kschlauc at vt.edu
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help




More information about the R-help mailing list