Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting only first character, along a specific order

Tags:

sorting

r

I have a character vector like this:

stuff <- c("3S", "AH", "2I", "B4", "AL")

And I have a "position" vector like this:

pos <- c("3", "B", "A", "2")

I want to use the last vector as a reference to sort the first one by looking only at the first character of each element; I don't care about the second character. That is, I want to write and a function like specialsort(stuff, pos), and my result should be c("3S", "B4", "AH", "AL", "2I").

like image 541
Celso Avatar asked Apr 03 '14 21:04

Celso


2 Answers

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"
like image 97
sgibb Avatar answered Nov 14 '22 23:11

sgibb


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.

like image 31
RoyalTS Avatar answered Nov 14 '22 23:11

RoyalTS