Sorting a Vector by ascending order

I have a vector like this -

MyVector <- c("2:3", "11:6", "9:10")

I am going to call this as x:y. I want to sort the values of x in ascending order.

So my sorted vector needs to look like,

"2:3", "9:10", "11:6"

and after sorting, I would like to output the values of Y in a different vector

FinalVector will look like:

"3", "10", "6"

Upvotes: 3

Views: 810

Answers (2)

989
989

Reputation: 12935

You could also do:

a <- as.numeric(unlist(strsplit(MyVector, ":")))
a[c(FALSE, TRUE)][order(a[c(TRUE, FALSE)])]

#[1]  3 10  6

Upvotes: 2

pogibas
pogibas

Reputation: 28379

MyVector <- c("2:3", "11:6", "9:10")
gsub(".*:", "", MyVector[order(as.numeric(gsub(":.*", "", MyVector)))])
[1] "3"  "10" "6" 

Explanation:

  • gsub(":.*", "", MyVector) - Extract part before : (eg., 2, 11, 9)
  • Turn them into numbers and get their order in original vector
  • Extract values from original vector in specified order
  • gsub(".*:", "" ...) - Delete part before :

Upvotes: 4

Related Questions