I have a vector called myvec<- c("B","C","D","A")
. I want to position C
and D
elements first and second then B
and A
.Thus the result should be C,D,B,A
. How can we get this done in R?
To just bring "C"
and "D"
to the front:
myvec <- c("B","C","D","A")
myvec[order(!myvec %in% c('C', 'D'))]
#[1] "C" "D" "B" "A"
To give a complete ordering:
myvec <- c("B","C","D","A")
order.vec <- c('C', 'D', 'B', 'A')
myvec[order(match(myvec, order.vec))]
# [1] "C" "D" "B" "A"
Example with a different input vector:
myvec <- sample(myvec, 20, T)
myvec[order(match(myvec, order.vec))]
# [1] "C" "C" "C" "C" "C" "C" "D" "D" "D" "D" "D" "D" "B" "B" "B" "A" "A" "A" "A" "A"
You can using factor
sort(factor(myvec <- sample(myvec, 20, T),c('C', 'D', 'B', 'A')))
[1] C C C D D D D D D B B B B B B A A A A A
Levels: C D B A
I generally use setdiff() for when I want to remove elements from a vector
myvec <- c("B","C","D","A")
put_first <- c("C", "D")
new_vec <- c(put_first, setdiff(myvec, put_first))
new_vec
# [1] "C" "D" "B" "A"
Edited If you want it to allow for multiples in the data.
myvec <- c("B", "B","C", "C","D", "D", "A", "A")
put_first <- c("C", "D")
new_vec <- c(myvec[myvec %in% put_first], myvec[!myvec %in% put_first])
new_vec
# [1] "C" "C" "D" "D" "B" "B" "A" "A"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.