The mutate() function helps you add new columns or change existing ones in a table of data easily.
mutate() for new columns in R Programming
Introduction
Syntax
R Programming
mutate(data_frame, new_column = expression, ...)
data_frame is your table of data.
You can add one or more new columns by giving each a name and a formula.
Examples
total by multiplying price and quantity.R Programming
mutate(df, total = price * quantity)
discount_price and tax calculated from price.R Programming
mutate(df, discount_price = price * 0.9, tax = price * 0.1)
category that labels rows as "Pass" or "Fail" based on score.R Programming
mutate(df, category = ifelse(score > 50, "Pass", "Fail"))
Sample Program
This program creates a small table with names, prices, and quantities. Then it adds a new column total by multiplying price and quantity. Finally, it prints the new table.
R Programming
library(dplyr) df <- data.frame(name = c("Anna", "Ben", "Cara"), price = c(10, 20, 15), quantity = c(2, 1, 3)) df_new <- mutate(df, total = price * quantity) print(df_new)
Important Notes
mutate() does not change the original data unless you save the result.
You can use many functions inside mutate() like ifelse(), arithmetic, or string functions.
Summary
mutate() adds or changes columns in your data.
Use it to create new information from existing data easily.
Remember to save the result if you want to keep the changes.
Practice
1. What does the
mutate() function do in R's dplyr package?easy
Solution
Step 1: Understand the purpose of mutate()
Themutate()function is designed to add new columns or change existing columns in a data frame.Step 2: Compare with other functions
Deleting rows is done byfilter(), sorting byarrange(), and merging byjoinfunctions, notmutate().Final Answer:
It adds new columns or modifies existing ones in a data frame. -> Option DQuick Check:
mutate()= add/change columns [OK]
Hint: mutate() changes or adds columns, not rows or merges [OK]
Common Mistakes:
- Confusing mutate() with filter() for rows
- Thinking mutate() merges data frames
- Assuming mutate() sorts data
2. Which of the following is the correct syntax to add a new column
total as the sum of columns a and b using mutate()?easy
Solution
Step 1: Check assignment inside mutate()
Insidemutate(), new columns are created with=, not with assignment operator<-.Step 2: Understand how to sum columns element-wise
To add columns element-wise, usea + b. Usingsum(a, b)sums all values together, not element-wise.a & bis a logical AND, not addition.Final Answer:
mutate(df, total = a + b) -> Option AQuick Check:
Use=and+for element-wise sum [OK]
Hint: Use = and + inside mutate() for new column sums [OK]
Common Mistakes:
- Using <- instead of = inside mutate()
- Using sum() instead of + for element-wise addition
- Using & instead of + for addition
3. Given the data frame
df <- data.frame(x = 1:3, y = 4:6), what will be the result of mutate(df, z = x * y)?medium
Solution
Step 1: Understand mutate() behavior
mutate()adds new columns without removing existing ones unless explicitly overwritten.Step 2: Calculate new column values
For each row,z = x * ymeans multiplying corresponding elements: 1*4=4, 2*5=10, 3*6=18.Final Answer:
A data frame with columns x, y, and z where z is the product of x and y. -> Option AQuick Check:
mutate() adds z = x * y element-wise [OK]
Hint: mutate() keeps old columns and adds new ones [OK]
Common Mistakes:
- Expecting mutate() to remove old columns
- Thinking mutate() cannot do arithmetic
- Assuming new column replaces all columns
4. What is wrong with this code snippet?
df <- data.frame(a = 1:3, b = 4:6) df %>% mutate(c = a + d)
medium
Solution
Step 1: Check column names in data frame
The data framedfhas columnsaandb, but no column namedd.Step 2: Understand mutate() behavior with missing columns
Trying to use a non-existent columndinsidemutate()causes an error because R cannot find it.Final Answer:
Columnddoes not exist indf, causing an error. -> Option BQuick Check:
Using unknown columns in mutate() causes error [OK]
Hint: Check all columns exist before using in mutate() [OK]
Common Mistakes:
- Assuming mutate() creates missing columns automatically
- Thinking pipe operator %>% is invalid here
- Believing syntax error due to missing comma
5. You have a data frame
df with columns score1 and score2. You want to add a new column average that is the average of these two scores, but only if both scores are greater than 0; otherwise, average should be NA. Which mutate() code correctly does this?hard
Solution
Step 1: Use ifelse() with correct condition
The condition requires bothscore1andscore2to be greater than 0, so use vectorized&insideifelse().Step 2: Calculate average or assign NA
If condition is true, calculate average as(score1 + score2) / 2, else assignNA.Final Answer:
mutate(df, average = ifelse(score1 > 0 & score2 > 0, (score1 + score2) / 2, NA)) -> Option CQuick Check:
Use ifelse() with & for both conditions [OK]
Hint: Use ifelse() with & to check both conditions [OK]
Common Mistakes:
- Using | instead of & to require both conditions
- Omitting ifelse() and always calculating average
- Using score1 & score2 without comparison
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
