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

2

8

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

Shoal answered 23/1, 2017 at 19:31 Comment(3)
x < y and y < xZip
Related: What are the R sorting rules of character vectors?.Nicobarese
alphabetical <- function(...) !is.unsorted(c(...)); alphabetical(x, y); alphabetical(y, x) works for any number of stringsAbducent
Z
14

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

Zip answered 23/1, 2017 at 19:49 Comment(2)
Just wanted you to get the credit since you had it in the comments 8 minutes prior to the accepted answer.Tusche
@RichScriven Appreciated.Zip
O
5
alphabetical <- function(x,y){x < y}
Odericus answered 23/1, 2017 at 19:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.