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"
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)gsub(".*:", "" ...) - Delete part before :You could also do:
a <- as.numeric(unlist(strsplit(MyVector, ":")))
a[c(FALSE, TRUE)][order(a[c(TRUE, FALSE)])]
#[1] 3 10 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With