Question

I have a character vector that contains strings starting with letters and with numbers:

sample.condition
[1] "1_t"   "2_t"   "3_t"   "4_t"   "5_t"   "6_t"   "7_t"   "GFP_t" "1_t"  
[10] "2_t"   "3_t"   "4_t"   "5_t"   "6_t"   "7_t"   "GFP_t"

The final sorted vector should have the elements containing "GFP" in the 1st positions:

sample.condition
[1] "GFP_t"   "GFP_t" "1_t"   "2_t"   "3_t"   "4_t"   "5_t"   "6_t"   "7_t"   "1_t"  
[10] "2_t"   "3_t"   "4_t"   "5_t"   "6_t"   "7_t"   

I have tried several sort arguments but got nowhere.

Was it helpful?

Solution

Find the strings not staring with a number. Create a logical index:

idx <- grepl("^[^0-9]", sample.condition)

Use this index for subsetting and sort the subsets. Then, combine both sorted subsets:

c(sort(sample.condition[idx]), sort(sample.condition[!idx]))

#  [1] "GFP_t" "GFP_t" "1_t"   "1_t"   "2_t"   "2_t"   "3_t"   "3_t"  
#  [9] "4_t"   "4_t"   "5_t"   "5_t"   "6_t"   "6_t"   "7_t"   "7_t"    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top