jO.
jO.

Reputation: 3512

re-order first and second column based on third while keeping it intact

Im trying to order two columns based on a third. Maybe it's more like reordering.

Dummy data

df <- as.data.frame(rbind(c('kex','id1A','id3B'),
                          c('sex','id1B','id1A'),
                          c('hex','id2A','id3C'),
                          c('flex','id3A','id1B'),
                          c('snex','id3B','ID2A'),
                          c('dex','id3C','id3A')))

The items in the first column are associated to the items in the second column. The third column includes the same items as the second, but in a different order. I want to (re)order the first and second column based the third while keeping its order intact. It's basically re-shuffling the second (and first on the fly) column so it (they) matches the third.

The output would look like this;

>df
V1   V2   V3
1 snex id3B id3B
2  kex id1A id1A
3  dex id3C id3C
4  sex id1B id1B
5  hex id2A ID2A
6 flex id3A id3A

Any pointer would be highly appreciated, thanks!

Upvotes: 1

Views: 121

Answers (2)

Alnair
Alnair

Reputation: 1058

Maybe

cbind(df[with(df,order(V3)),c(1,2)], df[,3])
    V1   V2 df[, 3]
2  sex id1B    id3B
4 flex id3A    id1A
5 snex id3B    id3C
6  dex id3C    id1B
1  kex id1A    ID2A
3  hex id2A    id3A

Upvotes: -3

Jilber Urbina
Jilber Urbina

Reputation: 61204

Try using rank and cbind

> cbind(df[rank(df$V3), -3], V3=df$V3)
    V1   V2   V3
5 snex id3B id3B
1  kex id1A id1A
6  dex id3C id3C
2  sex id1B id1B
3  hex id2A ID2A
4 flex id3A id3A

Upvotes: 4

Related Questions