Sorting only first character, along a specific order

You could use substring to extract the first letter of stuff and match to match your vector against the reference:

# find index in pos
i <- match(substring(stuff, 1, 1), pos)

# order by pos
o <- order(i)

stuff[o]
# [1] "3S" "B4" "AH" "AL" "2I"

I'm almost sure there's a simpler way to do it but this works:

specialsort <- function(stuff, pos) {
  stuff.pos <- sapply(pos,function(x) which(substring(stuff,1,1) == x))
  stuff[unlist(stuff.pos)]
}

specialsort(stuff,pos)

Careful though: This (and many other solutions) implicitly assumes that the pos vector is unique.

Tags:

Sorting

R