简体   繁体   中英

Indexing - Rearranging dataframe in R

Straight to the point, I have this data-frame which i want to re-number its index, if this is the right 'term' to use.

    month1  ID   
1     8.27  57
2     6.70  59
3     9.61  60
4    10.79  61
5    10.22  62

The catch is that these two columns come from different sql datasets that share some keys. And i need to re-index my table according to these keys.

For example there is this expression for (i in val2$TMEST_ID[i] == val$ID[i]) containing those two above-mentioned keys. The latest val$ID is actually the ID column already on my datafame.

So how can i re-arrange my data so i can have month1 values according to the above relationship?

Note that i am mostly interested in re-arranging rather than re-creating from start my dataframe.

I hope question is clear enough, if not please do ask for clarifications. thanks

I think this is what you want?

vec <- c(8,6,4)
head(mtcars[order(mtcars$cyl, match(mtcars$cyl, vec)),])

                mpg cyl  disp hp drat    wt  qsec vs am gear carb
Datsun 710     22.8   4 108.0 93 3.85 2.320 18.61  1  1    4    1
Merc 240D      24.4   4 146.7 62 3.69 3.190 20.00  1  0    4    2
Merc 230       22.8   4 140.8 95 3.92 3.150 22.90  1  0    4    2
Fiat 128       32.4   4  78.7 66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7 52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1 65 4.22 1.835 19.90  1  1    4    1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM