4. Consider the code: df <- data.frame(x=1:3, y=4:6); col <- df['x'] + 1. What is the error in this code?
medium
A. The column name 'x' is incorrect
B. You cannot add 1 to a dataframe
C. df['x'] returns a vector, so addition is valid
D. The dataframe df is not defined
Solution
Step 1: Analyze df['x'] type
df['x'] returns a one-column dataframe, not a vector.
Step 2: Understand addition operation
Adding 1 to a dataframe causes an error because arithmetic operations expect vectors or numbers.
Final Answer:
You cannot add 1 to a dataframe -> Option B
Quick Check:
Adding number to dataframe causes error = A [OK]
Hint: Use [[]] or $ to get vector before arithmetic [OK]
Common Mistakes:
Assuming df['x'] is a vector
Using wrong column name
Ignoring that df is defined
5. You want to add 5 to every value in the 'score' column of dataframe df and keep the result as a vector. Which code correctly does this?
hard
A. df.score + 5
B. df['score'] + 5
C. df[score] + 5
D. df[['score']] + 5
Solution
Step 1: Identify how to get vector column
df[['score']] extracts the 'score' column as a vector suitable for arithmetic.
Step 2: Check other options
df.score is invalid syntax in R (Python-style dot notation), df['score'] returns a dataframe causing error on addition, df[score] is invalid without quotes around column name.
Final Answer:
df[['score']] + 5 -> Option D
Quick Check:
Double brackets extract vector for math = D [OK]
Hint: Use double brackets to get vector for calculations [OK]
Common Mistakes:
Using single brackets returns dataframe, causing errors
Forgetting quotes around column name in []
Assuming df[score] works without quotes
Using Python-style dot notation (df.score)
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.