Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dataframe by vector r

Tags:

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

like image 822
user2795569 Avatar asked Jun 09 '26 19:06

user2795569


2 Answers

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.

like image 155
Ciarán Tobin Avatar answered Jun 12 '26 11:06

Ciarán Tobin


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
like image 36
juba Avatar answered Jun 12 '26 10:06

juba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!