Substrings with substr()
Part of the Logic & Flow section of Coddy's R journey. Lesson 1 of 64.
substr(x, start, stop) returns the characters of x from position start to position stop, both included. Positions start at 1, like vector indexes.
word <- "programming"
print(substr(word, 1, 7))
print(substr(word, 4, 6))Output:
[1] "program"
[1] "gra"To take characters from the end, compute the positions with nchar():
code <- "INV-2024-0042"
n <- nchar(code)
print(substr(code, n - 3, n))Output:
[1] "0042"A stop past the end is cut to the last character, and a start greater than stop gives an empty string:
print(substr("cat", 2, 10))
print(substr("cat", 3, 1))Output:
[1] "at"
[1] ""substr() works on every element of a character vector at once:
days <- c("Monday", "Tuesday", "Wednesday")
print(substr(days, 1, 3))Output:
[1] "Mon" "Tue" "Wed"Assigning to substr() overwrites characters in place. The string keeps its length:
id <- "user-0000"
substr(id, 6, 9) <- "1234"
print(id)Output:
[1] "user-1234"Challenge
EasyComplete short_code(city) so it returns the first three letters of city in capital letters. For london it returns LON.
The supplied code reads the city from the input and prints the returned value on its own line.
Try it yourself
short_code <- function(city) {
# Write your code here
""
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(short_code(input[1]), sep = "\n")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Substrings with substr()Formatting with sprintf()Splitting and JoiningSearching StringsReplacing TextRecap - Username Builder4Matrices
Creating MatricesIndexing MatricesRow and Column SummariesMatrix ArithmeticRecap - Seating Chart2Key-Value Lookups
Named Vector LookupsChecking KeysAdding and Removing KeysLooping Over NamesRecap - Stock Desk3Sets and Counting
Unique ValuesSet OperationsMembership TestsCounting with table()Recap - Event Guests6Functions as Values
Anonymous FunctionsPassing FunctionsReturning FunctionsClosures with StateRecap - Discount Rules9Data Frames
Creating Data FramesColumns and RowsFiltering RowsAdding and SortingRecap - Sales Report12Project - Expense Tracker
Recording ExpensesTotal SpendingPractice on your own: Online R compiler