Below are the solutions to these exercises on sorting and ordering.

############### # # # Exercise 1 # # # ############### x <- c(1, 3, 2, 5, 4) sort(x)

## [1] 1 2 3 4 5

sort(x, decreasing=T)

## [1] 5 4 3 2 1

############### # # # Exercise 2 # # # ############### x <- matrix(1:100, ncol=10) x1 <- x[order(-x[,2]), ] x2 <- x[, order(-x[2, ])] ############### # # # Exercise 3 # # # ############### x[, 1] <- sort(x[, 1], decreasing=T) ############### # # # Exercise 4 # # # ############### is.unsorted(women$height)

## [1] FALSE

is.unsorted(women$weight)

## [1] FALSE

women$bmi <- women$weight / women$height^2 * 703 is.unsorted(women$bmi)

## [1] TRUE

women <- women[order(women$bmi), sort(names(women))] ############### # # # Exercise 5 # # # ############### CO2 <- CO2[order(as.character(CO2$Plant)), ] CO2 <- CO2[order(CO2$uptake, as.character(CO2$Plant)), ] CO2 <- CO2[order(CO2$uptake, -xtfrm(as.character(CO2$Plant))), ] ############### # # # Exercise 6 # # # ############### df <- as.data.frame(matrix(sample(1:5, 2000, T), ncol=40)) df <- df[do.call(order, df), ] df <- df[do.call(order, -df), ] df <- df[do.call(order, rev(df)), ]

**What's next:**

- Explore all our (>1000) R exercises
- Find an R course using our R Course Finder directory
- Subscribe to receive weekly updates and bonus sets by email
- Share with your friends and colleagues using the buttons below

Fatih says

– For a descending order in exercise 3 , code should be:

sort(x[,1], decreasing = T)

Han de Vries says

Hi Fatih,

Thanks for pointing this out. We have updated the solution.