The code creates a data frame with two columns: x (numbers) and y (characters).
Step 2: Understand print output format
Printing a data frame shows row numbers and columns with their values in a table format.
Final Answer:
x y
1 1 a
2 2 b -> Option A
Quick Check:
Print data frame shows rows and columns [OK]
Hint: Print shows row numbers and columns in table form [OK]
Common Mistakes:
Ignoring row numbers in output
Confusing vector print with data frame print
Expecting error when none occurs
4. Identify the error in the following R code that tries to create a data frame:
df <- data.frame(age = c(20, 25), name = c("John"))
medium
A. Missing comma between vectors
B. Incorrect use of quotes around names
C. Vectors have different lengths causing recycling warning
D. data.frame() cannot mix numeric and character vectors
Solution
Step 1: Check vector lengths
The age vector has length 2, but name vector has length 1.
Step 2: Understand recycling rule
R recycles shorter vectors to match longer ones, causing a warning when lengths differ.
Final Answer:
Vectors have different lengths causing recycling warning -> Option C
Quick Check:
Unequal vector lengths cause recycling warning [OK]
Hint: Ensure all vectors have same length in data.frame() [OK]
Common Mistakes:
Assuming data.frame() needs all vectors same type
Thinking missing commas cause error here
Confusing quotes usage
5. You want to create a data frame from two vectors: ids = c(101, 102, 103) and scores = c(88, 92, 85). Then add a new column passed which is TRUE if score ≥ 90, otherwise FALSE. Which code correctly does this?
hard
A. All of the above
B. df <- data.frame(ids, scores, passed = scores >= 90)
D. df <- data.frame(ids, scores)
df$passed <- passed >= 90
Solution
Step 1: Check the one-line data.frame creation
df <- data.frame(ids, scores, passed = scores ≥ 90) correctly names columns from variable names and computes passed as logical vector.
Step 2: Eliminate incorrect options
The two-line option using if(scores ≥ 90, TRUE, FALSE) has invalid syntax for if. The other two-line uses undefined passed in passed ≥ 90. All of the above is false.