sort data frame according to the order of variables in another data frame

Dear R experts,

I have two data frames as follows
data1=data.frame(x=c(1,2,3),y=c(4,3,10))
data2=data.frame(var=c('x','y'),r=c(-1,2))
The column names in data1 correspond to the column "var" in data2.
I would like to sort data1 according to the information in data2. The absolute values of "r" indicate the importance of "var" and the sign of "r" indicates the directionality of sorting.

Because "y" has larger absolute r value than "x" in data2, sort data1 first with data1$y and then with data2$x
data1=data1[order(data1$y,data1$x),]

Because the sign of "x" is negative in data2, sort data1$x in an ascending fashion and because "y" is positive in data2, sort data1$y in a descending fashion.
data1=data1[order(-data1$y,data1$x),]

I can make this sorting automatic without rewriting the script every time the values in data2 change.Suggestion will be appreciated.

Best,
Veda

A reproducible example, called a reprex would be a huge help in working through the problem. Some representative data and the code used to get to your desired result would be great.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.