Data Wrangling: Subsetting vectors and factors Answer Key

Author

Will Gammerdinger

Published

July 1, 2025

Exercise 1

  1. Create a vector called alphabets with the following letters, C, D, X, L, F.
# Create a vector with the letters C, D, X, L, F
alphabets <- c("C", "D", "X", "L", "F")
  1. Use the associated indices along with [ ] to do the following:
  • Only display C, D and F
# Subset C, D and F from the alphabets vector
alphabets[c(1,2,5)]
[1] "C" "D" "F"
  • Display all except X
# Subset everything but X from the alphabets vector
alphabets[-3]
[1] "C" "D" "L" "F"
  • Display the letters in the opposite order (F, L, X, D, C)
# Reverse the order of the alphabets vector
alphabets[5:1]
[1] "F" "L" "X" "D" "C"

Exercise 2

Extract only those elements in samplegroup that are not KO (nesting the logical operation is optional).

# Create an boolean index vector for elements in samplegroup that are not "KO" 
idx <- samplegroup != "KO"

# Subset the samplegroup vector by the boolean index
samplegroup[idx]
[1] CTL CTL CTL OE  OE  OE 
Levels: CTL KO OE

Alternatively, you can use a nested approach:

# Subset the samplegroup vector by elements in samplegroup that are not "KO" 
samplegroup[samplegroup != "KO"]
[1] CTL CTL CTL OE  OE  OE 
Levels: CTL KO OE

Exercise 3

Use the samplegroup factor we created in a previous lesson, and relevel it such that KO is the first level followed by CTL and OE.

# Re-level the samplegroup factor vector with KO being the first level followed by CTL and OE
factor(samplegroup, levels = c("KO", "CTL", "OE"))
[1] CTL CTL CTL KO  KO  KO  OE  OE  OE 
Levels: KO CTL OE