lapply applies the function to each element of 1:3, returning a list of results.
Step 2: Calculate each element
For x=1,2,3, function(x) x*2 returns 2,4,6 respectively, stored as list elements.
Final Answer:
[[1]] 2 [[2]] 4 [[3]] 6 -> Option A
Quick Check:
lapply returns list of doubled values [OK]
Hint: lapply returns a list, not a vector [OK]
Common Mistakes:
Expecting a vector output instead of a list
Confusing lapply with sapply output
Thinking anonymous function causes error
4. Identify the error in this R code using an anonymous function:
result <- lapply(1:3, function(x) { x + })
medium
A. Anonymous functions cannot be used inside lapply
B. Missing value after '+' operator
C. Incorrect use of curly braces
D. Variable 'result' is not defined
Solution
Step 1: Analyze the anonymous function body
The function body has 'x +', which is incomplete because '+' needs a value after it.
Step 2: Identify the syntax error
This causes a syntax error due to missing operand after '+'. Other options are incorrect because anonymous functions are valid in lapply, curly braces are correctly used, and 'result' is defined.
Final Answer:
Missing value after '+' operator -> Option B
Quick Check:
Incomplete operator usage = syntax error [OK]
Hint: Check operators have both operands [OK]
Common Mistakes:
Assuming anonymous functions can't be used in lapply
Ignoring incomplete expressions inside function
Confusing variable definition errors with syntax errors
5. How can you use an anonymous function to filter even numbers from a vector v <- 1:6 using Filter() in R?
hard
A. Filter(function(x) x %% 2 == 0, v)
B. Filter(function(x) x / 2 == 0, v)
C. Filter(function(x) x %% 2 = 0, v)
D. Filter(function(x) x == 0, v)
Solution
Step 1: Understand filtering even numbers
Even numbers have zero remainder when divided by 2, so condition is x %% 2 == 0.
Step 2: Check each option's condition
Filter(function(x) x %% 2 == 0, v) correctly uses 'x %% 2 == 0'. Filter(function(x) x / 2 == 0, v) uses division instead of modulo, Filter(function(x) x %% 2 = 0, v) uses single '=', which is assignment not comparison, and Filter(function(x) x == 0, v) checks if x equals zero only.
Final Answer:
Filter(function(x) x %% 2 == 0, v) -> Option A
Quick Check:
Modulo equals zero filters even numbers [OK]
Hint: Use '%% 2 == 0' to check even numbers [OK]
Common Mistakes:
Using single '=' instead of '==' for comparison
Using division '/' instead of modulo '%%'
Filtering for x == 0 instead of even numbers
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.