Expecting output as a data frame instead of vector
4. What is wrong with this R code snippet to select the 3rd row and all columns from data frame df?
df[3]
medium
A. It selects the 3rd column, not the 3rd row
B. It causes a syntax error
C. It selects the 3rd row but drops columns
D. It returns all rows and columns
Solution
Step 1: Understand single bracket indexing with one index
Using one index like df[3] selects the 3rd column, not row.
Step 2: Identify correct way to select 3rd row
To select 3rd row and all columns, use df[3, ].
Final Answer:
It selects the 3rd column, not the 3rd row -> Option A
Quick Check:
df[3] = 3rd column, not row [OK]
Hint: Use df[row, ] to select rows, not df[row] [OK]
Common Mistakes:
Using single index to select rows
Expecting df[3] to select 3rd row
Confusing data frame and vector indexing
5. You have a data frame df with 5 rows and 4 columns named A, B, C, D. How do you select rows 2 to 4 and columns B and D using row and column indexing?
hard
A. df[2:4, c(2, 4)]
B. df[c(2,3,4), 2:4]
C. df[2:4, c("B", "D")]
D. df[2:4, c("2", "4")]
Solution
Step 1: Identify rows and columns to select
Rows 2 to 4 means indices 2, 3, 4; columns B and D are selected by names "B" and "D".
Step 2: Use correct syntax for row and column indexing
Use df[2:4, c("B", "D") ] to select rows 2-4 and columns named B and D.
Final Answer:
df[2:4, c("B", "D") ] -> Option C
Quick Check:
Row indices and column names combined correctly [OK]
Hint: Use row range and column names vector inside brackets [OK]
Common Mistakes:
Using numeric column indices instead of names
Passing column names as numbers in quotes
Selecting wrong rows or columns
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.