Grouping & Joining Data (flash cards)

Question 1

What does aggregation do to a data frame?

It combines rows into groups based on the values in one or more columns and then calculates summary statistics for each group.

Question 2

What two dplyr functions are used to aggregate data?

group_by() to make the groups, followed by summarize() to calculate the summary statistics

Question 3

df is short for Data Frame and represents the data table in the remaining cards

How do you calculate the mean of col_name_2 for each value of col_name_1?

df |>
  group_by(col_name_1) |>
  summarize(mean = mean(col_name_2))

Question 4

What does n() do inside summarize()?

Counts the number of rows in each group.

Question 5

How do you group by more than one column?

Pass multiple column names to group_by()

For example,

df |>
  group_by(col_name_1, col_name_2) |>
  summarize(mean = mean(col_name_3))

This produces one row for each unique combination of the two columns.

Question 6

What do we use to combine two or more tables?

Joins

Question 7

How do you combine df and df2 using their shared join_column?

inner_join(df, df2, join_by(join_column))

Question 8

Which rows does inner_join() keep?

Only rows that have matching values in both tables.

Question 9

How do you join three tables together?

Join two tables and then join the result with the third table.

df |>
  inner_join(df2, join_by(col_name_1)) |>
  inner_join(df3, join_by(col_name_2))

Question 10

What are three ways to extract a single column (col_name) from df as a vector?

df$col_name

df[["col_name"]]

pull(df, col_name)

Question 11

You have the vectors vector_1, vector_2, and vector_3.

How do you combine them into a data frame?

df <- data.frame(
  col_name_1 = vector_1,
  col_name_2 = vector_2,
  col_name_3 = vector_3
)

or to make a tibble:

df <- tibble(
  col_name_1 = vector_1,
  col_name_2 = vector_2,
  col_name_3 = vector_3
)

Question 12

How do you add a column that has the same value, 2026, in every row?

Use the single value in place of a vector.

df <- data.frame(
  col_name_1 = vector_1,
  col_name_2 = vector_2,
  year = 2026
)