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")
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With