What is wrong with this code if the goal is to get a numeric vector of squared values?
medium
A. Nothing is wrong; it returns a numeric vector.
B. The anonymous function is incorrect; it should use x*x instead of x^2.
C. The list elements should be named for lapply to work.
D. Using lapply returns a list, not a numeric vector.
Solution
Step 1: Understand output type of lapply
lapply always returns a list, even if function returns single values.
Step 2: Identify how to get numeric vector output
To get a numeric vector, sapply should be used instead of lapply.
Final Answer:
Using lapply returns a list, not a numeric vector. -> Option D
Quick Check:
lapply output is list, not vector [OK]
Hint: Use sapply for vector output, lapply always returns list [OK]
Common Mistakes:
Thinking lapply returns vector
Believing function syntax is wrong
Assuming names are required for lapply
5. You have a list of numeric vectors: data_list <- list(c(1,2), c(3,4,5), c(6)). You want to create a numeric vector of the means of each vector, but if a vector is empty, return NA for that element. Which code correctly does this using lapply or sapply?
hard
A. sapply(data_list, function(x) if(length(x) == 0) NA else mean(x))
B. lapply(data_list, function(x) if(length(x) == 0) NA else mean(x))
C. sapply(data_list, mean, na.rm=TRUE)
D. lapply(data_list, mean, na.rm=TRUE)
Solution
Step 1: Handle empty vectors with conditional inside function
The function checks if length is zero, returns NA; else returns mean.
Step 2: Use sapply to get numeric vector output
Using sapply simplifies the result to a numeric vector, which is desired.
Final Answer:
sapply(data_list, function(x) if(length(x) == 0) NA else mean(x)) -> Option A
Quick Check:
Conditional function + sapply for vector output [OK]
Hint: Use sapply with if-else inside function for conditional output [OK]
Common Mistakes:
Using lapply and expecting vector output
Not handling empty vectors explicitly
Passing na.rm=TRUE without checking empty vectors
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.