user2795569
user2795569

Reputation: 343

Sort dataframe by vector r

im having some trouble figuring out how to do this.

I want to sort a dataframe by a column containing factors that are the same as the factors I have in a list. It is important that the code doesn't change the order of the rows in each factor though.

Ideas?

edit:

salmon <- c("red", 3,7, 5)
bass <- c("red", 1,3,5)
shrimp <- c("blue", 1, 4, 2)
carp <- c("orange", 6, 6, 6)

dfex <- data.frame(salmon, bass, shrimp, carp)
dfex <- data.frame(t(dfex))

ordering <- c("blue", "orange", "red")

so the idea here is to reorder the dataframe by using the ordering vector

Upvotes: 3

Views: 3537

Answers (2)

Ciar&#225;n Tobin
Ciar&#225;n Tobin

Reputation: 7526

A combination of match() and order() should do it.

dfex[order(match(dfex[[1]], ordering)), ]

match() will tell you the index position of each value in the first column as found in ordering. And sorting by these positions will result in an order that matches the order of ordering.

Upvotes: 12

juba
juba

Reputation: 49033

First, the way you build your data frame is a bit complicated. You can do something like the following instead :

dfex <- data.frame(v1=c("salmon","shrimp","carp"),
                   v2=c("red","blue","orange"),
                   v3=c(3,1,6),
                   v4=c(7,4,6),
                   v5=c(5,2,6))

Then you can order your data frame by using row names :

order <- c("blue", "orange", "red")
rownames(dfex) <- dfex$v2
dfex[order,]     

Which gives :

           v1     v2 v3 v4 v5
blue   shrimp   blue  1  4  2
orange   carp orange  6  6  6
red    salmon    red  3  7  5

Upvotes: 6

Related Questions