ykjk ykjk - 24 days ago 8
R Question

Sort/Order df according to 2 values from another df

I have 2 df that both contain the same first 2 columns:

date |symbol| cell3

2010-01-05| AAPB |12300

2010-01-05| AZT |45600

2010-01-05| AUMO |78900

and df 2 (

buys
) with pretty much the same info, but the symbols are not in the same order as df1 (
new_panel
).

I would like to order df2 in the same way that df1 is set up.

I tried
buys[sort(order(buys)[new_panel])]
but it does not seem to work for my case.

Edit:
I need to sort it by date AND symbol.

I also tried this, but it doesn't work for duplicates
require(gdata)

new_panel <- reorder.factor(new_panel$symbol, new.order=buys$symbol)

Answer

If the second data frame has the same information, you can sort that by date and then use symbol from the first data frame as a target vector for setting up the second data frame.

buys[order((as.Date(buys$date, format="%Y-%m-%d")),match(new_panel$symbol, buys$symbol)),,]
Comments