Sorting Data in R

Load Packages

packages <- c("tidyverse")

packages <- lapply(packages, FUN = function(x) {

if(!require(x, character.only = TRUE)) {


library(x, character.only = TRUE)}})

Load Dataset

df <- diamonds

Get Top 5 Rows

head(df, 5)

Get Bottom 5 Rows

tail(df, 5)

Sorting Data

df <- df[order(df$carat),]

Sort by carat and price

df <- df[order(df$carat, df$price),]

Sort by carat (ascending) and price (descending)

df <- df[order(df$carat, -df$price),]

Extract Rows and Columns

All Rows and All Columns


First row and all columns


First two rows and all columns


First and third row and all columns

df[ c(1,3), ]

First Row and 2nd and third column

df[1, 2:3]

First, Second Row and Second and Third Column

df[1:2, 2:3]

Just First Column with All rows

df[, 1]

First and Third Column with All rows


Sabalico Logo
Sabalytics Logo
Senty Logo
SEO Guide Logo
World Map Logo
rStatistics Logo
Day Map Logo
Time Zone Logo
Galaxy View Logo
Periodic Table Logo
My Location Logo
Weather Track Logo
Sprite Sheet Logo
Barcode Generator Logo
Test Speed Logo
Website Tools Logo
Image Tools Logo
Color Tools Logo
Text Tools Logo
Finance Tools Logo
File Tools Logo
Data Tools Logo
History of Humanity - History Archive Logo
History of Humanity - History Mysteries Logo
History of Humanity - Ancient Mesopotamia Logo
History of Humanity - Persian Empire Logo
History of Humanity - Alexander the Great Logo
History of Humanity - Roman History Logo
History of Humanity - Punic Wars Logo
History of Humanity - Golden Age of Piracy Logo
History of Humanity - Revolutionary War Logo