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
A. mutate(df, average = (score1 + score2) / 2)
B. mutate(df, average = ifelse(score1 > 0 | score2 > 0, (score1 + score2) / 2, NA))
C. mutate(df, average = ifelse(score1 > 0 & score2 > 0, (score1 + score2) / 2, NA))
D. mutate(df, average = ifelse(score1 & score2, (score1 + score2) / 2, NA))
Solution
Step 1: Use ifelse() with correct condition
The condition requires both score1 and score2 to be greater than 0, so use vectorized & inside ifelse().
Step 2: Calculate average or assign NA
If condition is true, calculate average as (score1 + score2) / 2, else assign NA.
Final Answer:
mutate(df, average = ifelse(score1 > 0 & score2 > 0, (score1 + score2) / 2, NA)) -> Option C
Quick 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 unknownstrongwhile earning +1 Grip toward your certificate.