Sort dataframe by column in R

Sort dataframe by columns in R?

We can sort the dataframe by column in R. Sort can be either ascending or descending order.

Examples:

1. Create Dataframe

df< -data.frame(x=c("A","B","K","M","L"), y=c(4,7,6,9,11), z=c(1,4,2,3,0))

> df x y z 1 A 4 1 2 B 7 4 3 K 6 2 4 M 9 3 5 L 11 0

2. Sort data frame ascending order by using columns name z in ascending order.

> df[with(df,order(z)),] x y z 5 L 11 0 1 A 4 1 3 K 6 2 4 M 9 3 2 B 7 4

3. Sort data frame ascending order by using columns name z in descending order.

> df[with(df,order(-z)),] x y z 2 B 7 4 4 M 9 3 3 K 6 2 1 A 4 1 5 L 11 0

Same can be obtained using order function.

1. Sort data frame ascending order by using columns name z in ascending order.

> df[order(df[,3]),] x y z 5 L 11 0 1 A 4 1 3 K 6 2 4 M 9 3 2 B 7 4

2. Sort data frame ascending order by using columns name z in ascending order.

> df[order(-df[,3]),] x y z 2 B 7 4 4 M 9 3 3 K 6 2 1 A 4 1 5 L 11 0

CheapSexCams
Responses are currently closed, but you can trackback from your own site.

Comments are closed.

Powered by k2schools
%d bloggers like this: