Reputation: 328
I have seen many similar threads however, the examples I've seen tend to have a more linear trend to them and as such, do not apply to my problem.
I have a table that looks as such:
x1 x2
a up
k up
h up
d up
p up
. .
. .
And another table with the EXACT same entries over x1, where NROW(table1) == NROW(table2), as such:
x1 x2
k up
a down
d down
. .
. .
I want to reorder table1 based off x1 in table2, where the x1 and x2 variables will remain consistent in the output; a for example to still be up.
where the output would look like this:
x1 x2
k up
a up
d up
. .
. .
Upvotes: 0
Views: 985
Reputation: 1718
if you want to keep the table2$x1 order :
merge(table1,table2,by="x1")
x1 x2.x x2.y
1 a up up
2 d up down
3 k up up
and you can choose which column to delete
Upvotes: 1
Reputation: 2551
You can use match()
to find the positions of x1 from the second table in the first table and re-order. Here's the result in your example. Let's reorder tab1
by tab2
:
tab1 <- data.frame(x1 = c("a", "k", "h", "d", "p"),
x2 = c("up", "up", "up", "up", "up"))
tab2 <- data.frame(x1 = c("k", "a", "d"),
x2 = c("up", "up", "down"))
idx <- match(tab2$x1, tab1$x1)
tab1[idx,]
This results in:
x1 x2
1 k up
2 a up
3 d up
Upvotes: 1