0

I'm a newbie, and now I have a problem: I have vector A, which is arranged in order of "T1、T2、T3、T5、T7、T8、T4、T6、T9", but now I want it to be arranged in order of "T1-T9" and correspond to the correct values. What do I need to do?

A<-c(0.301,0.218,0.153,0.116,0.085,0.056,0.033,0.024,0.013)
names(A)<-c("T1","T2","T3","T5","T7","T8","T4","T6","T9")
A
Phil
  • 7,287
  • 3
  • 36
  • 66
WHB533
  • 3
  • 1

1 Answers1

4

For the example shared using order/sort would work directly :

A[order(names(A))]

#   T1    T2    T3    T4    T5    T6    T7    T8    T9 
#0.301 0.218 0.153 0.033 0.116 0.024 0.085 0.056 0.013 

But if "T" values go beyond 9 this will not work. For example,

A<-c(0.301,0.218,0.153,0.116,0.085,0.056,0.033,0.024,0.013, 0.1)
names(A)<-c("T1","T2","T3","T5","T7","T8","T4","T10","T9", "T6")
A[order(names(A))]

#   T1   T10    T2    T3    T4    T5    T6    T7    T8    T9 
#0.301 0.024 0.218 0.153 0.033 0.116 0.100 0.085 0.056 0.013 

This is because order/sort would lexicographically sort the names.

In which case you can use gtools::mixedorder/gtools::mixedsort

A[gtools::mixedorder(names(A))]
#   T1    T2    T3    T4    T5    T6    T7    T8    T9   T10 
#0.301 0.218 0.153 0.033 0.116 0.100 0.085 0.056 0.013 0.024 

In base R, you can remove all non-numerics, convert to integer and order

A[order(as.numeric(gsub('\\D', '', names(A))))]
#Or
#A[order(as.numeric(sub('T', '', names(A))))]

EDIT

Based on comments from OP if you want data in custom order you can use match + order :

x <- c("PED", "CADP", "GWP", "EP", "POCP", "HI", "AP", "ODP", "RI")
correct_order <- c("PED", "CADP", "GWP", "AP", "EP", "ODP", "POCP", "HI", "RI")

x[order(match(x, correct_order))]

#[1] "PED"  "CADP" "GWP"  "AP"   "EP"   "ODP"  "POCP" "HI"   "RI" 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • thank you,this answer can indeed solve the problem,but if the vector A name is c(“PED”, “CADP”, “GWP”, “EP”, “POCP”, “HI ”, “AP”, “ODP”, "RI"), I want to the value of A to follow in this order c(“PED”, “CADP”, “GWP”, “AP”, “EP”, “ODP”, “POCP”, “HI ”, "RI"),what can I do? – WHB533 Oct 11 '20 at 05:03
  • there is no logic,just I want to do it in this order,Is there a program that can implement this custom order? – WHB533 Oct 11 '20 at 05:22
  • @WHB533 Yes, check the last part in updated answer. You can use `match` with `order`. – Ronak Shah Oct 11 '20 at 05:50