for Loops Answer Key

Author

Will Gammerdinger

Published

July 1, 2025

Exercise 1

Create the following dataframes:

# Gene-expression measurements for five samples
gene_expression <- data.frame(
  Sample_ID = c("S01", "S02", "S03", "S04", "S05"),
  TP53_expression = c(12.4, 8.7, 15.1, 10.2, 9.8)
)

# Cytokine measurements for five samples
cytokine_data <- data.frame(
  Sample = c("S03", "S01", "S06", "S02", "S04"),
  IL6_concentration = c(4.8, 2.1, 7.3, 3.5, 5.2)
)
# Print out gene_expression
gene_expression
  Sample_ID TP53_expression
1       S01            12.4
2       S02             8.7
3       S03            15.1
4       S04            10.2
5       S05             9.8
# Print out cytokine_data
cytokine_data
  Sample IL6_concentration
1    S03               4.8
2    S01               2.1
3    S06               7.3
4    S02               3.5
5    S04               5.2
  1. Use merge() to combine the data frames without changing any of the column names.

Hint: Look up the arguments for by.x and by.y

# Merge the gene_expression and cytokine_data dataframes
merged_data <- merge(x = gene_expression,
      y = cytokine_data,
      by.x = "Sample_ID",
      by.y = "Sample")

# Print out merged_data
merged_data
  Sample_ID TP53_expression IL6_concentration
1       S01            12.4               2.1
2       S02             8.7               3.5
3       S03            15.1               4.8
4       S04            10.2               5.2
  1. Is Sample_ID or Sample retained as the column name?

Sample_ID is retained as the column name.

  1. How many rows are in the merged data frame?

There are four rows.

  1. Which samples are included in the result?

Samples S01, S02, S03 and S04 are all retained.

  1. Which samples were excluded, and why?

Sample S05 is excluded because it is not in cytokine_data and Sample S06 is excluded, because it is not in gene_expression.

  1. Add the all = TRUE argument to your merge command. How does the output change?
# Merge the gene_expression and cytokine_data dataframes with all
merged_data_all <- merge(x = gene_expression,
      y = cytokine_data,
      by.x = "Sample_ID",
      by.y = "Sample",
      all = TRUE)

# Print out merged_data
merged_data_all
  Sample_ID TP53_expression IL6_concentration
1       S01            12.4               2.1
2       S02             8.7               3.5
3       S03            15.1               4.8
4       S04            10.2               5.2
5       S05             9.8                NA
6       S06              NA               7.3

The rows that were absent in one of the tables are now retained and have NA values.