I have two sets of data frames, the first set is like:
df1 = subset(mtcars, select="gear")
head(df1)
gear
Mazda RX4 4
Mazda RX4 Wag 4
Datsun 710 4
Hornet 4 Drive 3
Hornet Sportabout 3
The format of the second set is like this:
df2 = t(mtcars)[1:4,]
head(df2)
Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout
mpg 21 21 22.8 21.4 18.7
cyl 6 6 4.0 6.0 8.0
disp 160 160 108.0 258.0 360.0
hp 110 110 93.0 110.0 175.0
The row names of df1 are the column names of df2.
I would like to take all the cars that have the same gear in df1 as a group. Then calculate the mean of mpg and disp together only for the cars, followed by sorting the groups based on their means from high to low.
In this case, the expected results would be (since the cars with gear 3 have a higher mean of mpg and disp than the ones with gear 4):
Hornet 4 Drive Hornet Sportabout Mazda RX4 Mazda RX4 Wag Datsun 710
mpg 21.4 18.7 21 21 22.8
cyl 6.0 8.0 6 6 4.0
disp 258.0 360.0 160 160 108.0
hp 110.0 175.0 110 110 93.0
I hope this is clear to you. I do not know how to apply the groups (gear) of df1 to df2 and order df2 based on the mean of the groups. Thanks!