Search code examples
ralphabetical

R - Can you compare which value is first in alphabetical order?


If I have the values:

x <- 'random'
y <- 'word'

Can I do a test to see if x alphabetically comes before or after y? In this example something similar to a function that would produce:

alphabetical(x,y) -> True

alphabetical(y,x) -> False


Solution

  • The built-in comparison operators work fine on strings.

    x < y
    [1] TRUE
    y < x
    [1] FALSE
    

    Note the details in the help page ?Comparison, or perhaps more intuitively, ?`<`, especially the importances of locale:

    Comparison of strings in character vectors is lexicographic within the strings using the collating sequence of the locale in use [...]

    Beware of making any assumptions about the collation order