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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With