Skip to content
R for the Rest of Us Logo

Fundamentals of R

arrange()

Transcript

Click on the transcript to go to that point in the video. Please note that transcripts are auto generated and may contain minor inaccuracies.

View code shown in video
# Load Packages -----------------------------------------------------------

library(tidyverse)

# Import Data -------------------------------------------------------------

penguins <-
  read_csv("penguins.csv")

# arrange() ---------------------------------------------------------------

# With arrange(), we can reorder rows in a data frame based on the values
# of one or more variables.
# R arranges in ascending order by default.

penguins |>
  arrange(bill_length_mm)

penguins |> 
  arrange(species, island) |> 
  view()

# We can also arrange in descending order using desc().

penguins |>
  arrange(desc(bill_length_mm))

# We often use arrange() at the end of pipelines to display things in order.

penguins |>
  group_by(island, year) |>
  summarize(mean_bill_length = mean(bill_length_mm, na.rm = TRUE)) |>
  arrange(desc(mean_bill_length))

Your Turn

# Load Packages -----------------------------------------------------------

# Load the tidyverse package

library(tidyverse)

# Import Data -------------------------------------------------------------

penguins <- read_csv("penguins.csv")
			
# arrange() ---------------------------------------------------------------

# Use arrange() to display the penguins data frame in order by body mass

# YOUR CODE HERE

# Now display the penguins data in descending order by body mass

# YOUR CODE HERE

# Create a pipeline that does the following:
# 1. Filters to only keep penguins on Biscoe island
# 2. Drops any rows with NA values for the body_mass_g or sex variables
# 3. Calculates the average body mass by sex
# 4. Displays the result in descending order by average body mass

# YOUR CODE HERE

Learn More

To learn more about the arrange() function, check out Chapter 3 of R for Data Science.

Have any questions? Put them below and we will help you out!

You need to be signed-in to comment on this post. Login.