简体   繁体   English

索引-在R中重新排列数据帧

[英]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. 问题是这两列来自共享某些键的不同sql数据集。 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. 例如,有一个表达式for (i in val2$TMEST_ID[i] == val$ID[i])中的for (i in val2$TMEST_ID[i] == val$ID[i])包含上述两个键。 The latest val$ID is actually the ID column already on my datafame. 最新的val$ID实际上是我的数据资料库中已有的ID列。

So how can i re-arrange my data so i can have month1 values according to the above relationship? 那么如何重新排列我的数据,以便根据上述关系获得month1值?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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