Hint: Count characters carefully; substring includes both start and end [OK]
Common Mistakes:
Counting length as 10 instead of 11
Extracting one extra character in substring
Confusing substring end position as exclusive
4. The following code is intended to extract "data" from the string "database" but it gives wrong output. What is the error?
text <- "database"
result <- substring(text, 1, 3)
print(result)
medium
A. The string variable is misspelled
B. substring function syntax is wrong
C. nchar should be used instead of substring
D. Start and end positions are incorrect; should be 1 to 4
Solution
Step 1: Check the substring positions used
substring(text, 1, 3) extracts characters 1 to 3: "dat" from "database".
Step 2: Identify correct positions for "data"
"data" is characters 1 to 4, so end position should be 4, not 3.
Final Answer:
Start and end positions are incorrect; should be 1 to 4 -> Option D
Quick Check:
substring("database", 1, 4) = "data" [OK]
Hint: Remember substring end position is inclusive [OK]
Common Mistakes:
Using end position one less than needed
Confusing substring with nchar usage
Assuming substring excludes end position
5. You have a vector of strings: words <- c("apple", "banana", "cherry"). Write R code using substring and nchar to create a new vector containing the last 3 characters of each word. Which code snippet does this correctly?
hard
A. substring(words, nchar(words), nchar(words)+2)
B. substring(words, 1, 3)
C. substring(words, nchar(words)-2, nchar(words))
D. substring(words, nchar(words)-3, nchar(words)-1)
Solution
Step 1: Understand how to get last 3 characters
For each word, last 3 characters start at position (length - 2) and end at length. Use nchar(words) to get length.
Step 2: Use substring with vectorized start and end
substring(words, nchar(words)-2, nchar(words)) extracts last 3 characters for each word correctly.
Step 3: Check other options
substring(words, 1, 3) extracts first 3 characters, C uses invalid end position, D extracts wrong positions.
Final Answer:
substring(words, nchar(words)-2, nchar(words)) -> Option C
Quick Check:
Last 3 chars of "banana" = "ana" [OK]
Hint: Use nchar(word)-2 as start for last 3 chars [OK]
Common Mistakes:
Using fixed start positions instead of dynamic
Off-by-one errors in start or end positions
Assuming substring end is exclusive
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.