How to re-arrange the rows in a Data Frame using the values in a column.
First we must build the data frame.
Build Data Frame
This data frame will have two columns, one for names and one for ages. We shall call it `df’
> names<-c('jose','shaniqua','Latoya') > age<-c(12,54,32)
Now we can put both vectors into the data frame.
> df<-data.frame('Name'=names,'Age'=age) # we can now check it.. df Name Age 1 jose 12 2 shaniqua 54 3 Latoya 32
Ascending Order
We will now order the rows according to age in ascending order, where we go from the smallest to the largest.
> df[order(df$'Age'),] # wich return Name Age 1 jose 12 3 Latoya 32 2 shaniqua 54
Descending Order
Now we will order the rows in descending alphabetical order (using the names), where we will go from z to a.
We can do this by using the rev()
function, like so…
> df[rev(order(df$'Name')),] # which returns Name Age 2 shaniqua 54 3 Latoya 32 1 jose 12
DONE!
One reply on “Ordering Rows in a Data Frame – R”
What about alphabetic order?