I am trying to reorder a numeric vector current_qty
using its name according to another vector trade_order
.
After a simple match, they give me some weird arrangement.
current_qty <- getQuantity(trades)
print(names(current_qty))
[1] "ivvb11" "lft20210301" "ltn20180101" "ntnb20200815" "pibb11"
print(trade_order)
[1] "pibb11" "ivvb11" "lft20210301" "ntnb20200815" "ltn20180101"
current_qty <- current_qty[match(names(current_qty), trade_order)]
print(current_qty)
lft20210301 ltn20180101 pibb11 ntnb20200815 ivvb11
2.15 42.59 50.00 3.89 60.00
Now the funny part. If I run the same match function twice. It works.
current_qty <- getQuantity(trades)
print(names(current_qty))
[1] "ivvb11" "lft20210301" "ltn20180101" "ntnb20200815" "pibb11"
print(trade_order)
[1] "pibb11" "ivvb11" "lft20210301" "ntnb20200815" "ltn20180101"
current_qty <- current_qty[match(names(current_qty), trade_order)]
current_qty <- current_qty[match(names(current_qty), trade_order)]
print(current_qty)
pibb11 ivvb11 lft20210301 ntnb20200815 ltn20180101
50.00 60.00 2.15 3.89 42.59
What am I doing wrong? Is there another way to do it?
From
help(match)
:"match returns a vector of the positions of (first) matches of its first argument in its second."
So it looks at each element in
names(current_qty)
and returns the position of it intrade_order
. So for example it sees"ivvb11"
in the second position ontrade_order
. Then this gets passed to your subset where it reorders things. So what this will do is it will move the element in position 2 ofcurrent_qty
("lft20210301"
) to the first position.Thus, you can see that you should reverse the order of the args you pass to match and you will be fine:
current_qty[match(trade_order, names(current_qty))]