is.numeric(num_vec) returns TRUE because num_vec is numeric.
Final Answer:
TRUE -> Option A
Quick Check:
as.numeric() converts, is.numeric() confirms [OK]
Hint: as.numeric() converts, is.numeric() checks type [OK]
Common Mistakes:
Expecting FALSE because original was character
Thinking as.numeric() returns character
Confusing is.numeric() with as.numeric()
4. Identify the error in the following R code snippet:
val <- "123abc"
num_val <- as.numeric(val)
print(num_val)
medium
A. No error, prints 123
B. Syntax error due to quotes
C. Prints NA with a warning
D. Prints 0 without warning
Solution
Step 1: Attempt to convert mixed string to numeric
as.numeric("123abc") cannot convert because of non-numeric characters.
Step 2: Result of conversion
It returns NA and shows a warning about NAs introduced by coercion.
Final Answer:
Prints NA with a warning -> Option C
Quick Check:
Invalid numeric conversion = NA + warning [OK]
Hint: Invalid numeric strings convert to NA with warning [OK]
Common Mistakes:
Expecting partial numeric conversion
Ignoring warning messages
Assuming syntax error due to quotes
5. You have a list lst <- list("5", 10, "abc", "15.5"). Which R code correctly converts all elements to numeric, replacing non-convertible values with 0?
hard
A. sapply(lst, function(x) if(is.na(as.numeric(x))) 0 else as.numeric(x))
B. sapply(lst, function(x) as.numeric(x))
C. sapply(lst, function(x) if(is.na(as.numeric(x))) as.numeric(x) else 0)
D. sapply(lst, function(x) if(is.numeric(x)) x else 0)
Solution
Step 1: Convert each element to numeric and check for NA
Use as.numeric(x) inside a function and check if result is NA.
Step 2: Replace NA with 0, else keep numeric value
If as.numeric(x) is NA, return 0; otherwise return the numeric value.
Final Answer:
sapply(lst, function(x) if(is.na(as.numeric(x))) 0 else as.numeric(x)) -> Option A
Quick Check:
Replace NA with 0 using conditional inside sapply [OK]
Hint: Use is.na(as.numeric(x)) to detect and replace [OK]
Common Mistakes:
Not checking for NA after conversion
Replacing numeric values incorrectly
Confusing condition logic in if-else
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.