Inconsistent match function, if I run twice works (R)

74 views Asked by At

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?

1

There are 1 answers

1
stanekam On BEST ANSWER

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 in trade_order. So for example it sees "ivvb11" in the second position on trade_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 of current_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))]