Inconsistent match function, if I run twice works (R) -
i trying reorder numeric vector current_qty
using name according vector trade_order
.
after simple match, give me 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 funny part. if run same match function twice. 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 doing wrong? there way it?
from help(match)
:
"match returns vector of positions of (first) matches of first argument in second."
so looks @ each element in names(current_qty)
, returns position of in trade_order
. example sees "ivvb11"
in second position on trade_order
. gets passed subset reorders things. move element in position 2 of current_qty
("lft20210301"
) first position.
thus, can see should reverse order of args pass match , fine:
current_qty[match(trade_order, names(current_qty))]
Comments
Post a Comment