Recall & Review
beginner
How do you add a new column to a data frame in R?
You can add a new column by assigning a vector to a new column name using the $ operator or bracket notation. For example,
df$new_column <- c(1, 2, 3) adds a column named new_column.Click to reveal answer
beginner
What is the syntax to remove a column from a data frame in R?
You can remove a column by setting it to NULL:
df$column_to_remove <- NULL. This deletes the column from the data frame.Click to reveal answer
intermediate
What happens if you assign a vector of different length than the number of rows when adding a column?
R will recycle the vector to match the number of rows, repeating the values to fill the column. A warning is given if its length does not divide evenly into the number of rows.
Click to reveal answer
intermediate
How can you add multiple columns at once to a data frame?
You can add multiple columns by assigning a data frame or list to new columns. For example,
df[c('col1', 'col2')] <- list(c(1,2), c(3,4)) adds two columns.Click to reveal answer
intermediate
Can you remove multiple columns at once? How?
Yes, by setting multiple columns to NULL using their names in brackets:
df[c('col1', 'col2')] <- NULL removes both columns.Click to reveal answer
Which of the following adds a new column named 'age' with values 25, 30, 35 to data frame df?
✗ Incorrect
Option D correctly assigns a numeric vector of length 3 to the new column 'age'.
How do you remove the column 'salary' from data frame df?
✗ Incorrect
Setting df$salary to NULL deletes the column from the data frame.
What happens if you add a column with a vector shorter than the number of rows?
✗ Incorrect
R recycles shorter vectors to fill the column, issuing a warning if the length does not divide evenly.
Which syntax adds two columns 'x' and 'y' at once to df?
✗ Incorrect
Assigning a list of vectors to multiple columns using bracket notation adds them correctly.
How to remove columns 'a' and 'b' from df in one step?
✗ Incorrect
Setting multiple columns to NULL at once removes them from the data frame.
Explain how to add a new column to a data frame in R and what happens if the vector length differs from the number of rows.
Think about how R handles vectors when adding columns.
You got /3 concepts.
Describe the methods to remove one or multiple columns from a data frame in R.
Consider how NULL affects data frame columns.
You got /3 concepts.