Using the match() Function Answer Key

Author

Will Gammerdinger

Published

December 7, 2025

Exercise 1

Now that we know how to reorder using indices, let’s try to use it to reorder the contents of one vector to match the contents of another. Let’s create the vectors first and second as detailed below:

# Create new second vector in a different order
first <- c("A","B","C","D","E")
second <- c("B","D","E","A","C")
  1. How would you reorder the second vector to match first?
# Reordering second vector to match the first vector
second[c(4, 1, 5, 2, 3)]
[1] "A" "B" "C" "D" "E"

Exercise 2

  1. After talking with your collaborator, it becomes clear that sample2 and sample9 were actually from a different mouse background than the other samples and should not be part of our analysis. Create a new variable called subset_rpkm that has these columns removed from the rpkm_ordered data frame.
# Remove samples 2 and 9
subset_rpkm <- rpkm_ordered[ , c(1,3:8,10:12)]

Alternatively, you could use:

# Remove samples 2 and 9 alternative
subset_rpkm <- rpkm_ordered[ , -c(2,9)]
  1. Use the match() function to subset the metadata data frame so that the row names of the metadata data frame match the column names of the subset_rpkm data frame.
# Use match to reorder metadata
idx <- match(colnames(subset_rpkm), rownames(metadata))
metadata[idx, ]
         genotype celltype replicate
sample1        Wt    typeA         1
sample3        Wt    typeA         3
sample4        KO    typeA         1
sample5        KO    typeA         2
sample6        KO    typeA         3
sample7        Wt    typeB         1
sample8        Wt    typeB         2
sample10       KO    typeB         1
sample11       KO    typeB         2
sample12       KO    typeB         3