Sort only the first character in a specific order

I have a character vector, for example:

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

And I have a "position" vector:

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

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

It drives me crazy.: -/

+6
source share
4 answers

You can use substring to extract the first letter of stuff and match to match your vector by 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" 
+7
source

I'm pretty sure there is an easier way to do this, 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) 

Caution: this (and many other solutions) implies that the pos vector is unique.

+2
source

You can do this with the help of clever (so to speak) manipulations with transposition to factors :

 stuff[order(factor(sapply(stuff,function(x)unlist(strsplit(x,''))[1]),levels=pos))] 

edited to add some clarification and simplify:

The first part will be to isolate only the first character of your material vector. This can be done with:

 > sapply(stuff,function(x)unlist(strsplit(x,''))[1]) 3S AH 2I B4 AL "3" "A" "2" "B" "A" 

You can then convert this to factors using the pos vector as levels:

 > factor(sapply(stuff,function(x)unlist(strsplit(x,''))[1]),levels=pos) 3S AH 2I B4 AL 3 A 2 BA Levels: 3 BA 2 

Finally, you can get the correct order from these factors:

 > order(factor(sapply(stuff,function(x)unlist(strsplit(x,''))[1]),levels=pos)) [1] 1 4 2 5 3 

The finish line just takes a subset of your original stuff vector:

 > stuff[order(factor(sapply(stuff,function(x)unlist(strsplit(x,''))[1]),levels=pos))] [1] "3S" "B4" "AH" "AL" "2I" 
0
source

to try

 stuff <- c("3S", "AH", "2I", "B4", "AL") pos <- c("3", "B", "A", "2") stuff.df = data.frame(stuff,pos = substr(stuff,1,1)) merge(data.frame(pos),stuff.df,sort = F) 

The "pos" column of the sorted data.frame is what you want

0
source

All Articles