Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a Vector by ascending order

Tags:

r

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"
like image 377
Siddharth Thanga Mariappan Avatar asked Aug 29 '26 11:08

Siddharth Thanga Mariappan


2 Answers

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 :
like image 197
pogibas Avatar answered Sep 01 '26 06:09

pogibas


You could also do:

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

#[1]  3 10  6
like image 28
989 Avatar answered Sep 01 '26 04:09

989



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!