Splitting and Joining
Part of the Logic & Flow section of Coddy's R journey. Lesson 3 of 64.
strsplit(x, split) cuts a string at every separator. It returns a list with one character vector per input string, so take [[1]] to get the pieces of a single string.
csv <- "red,green,blue"
parts <- strsplit(csv, ",")[[1]]
print(parts)
print(length(parts))Output:
[1] "red" "green" "blue"
[1] 3paste() goes the other way. With collapse, it joins the elements of one vector into a single string with the collapse text between them. sep goes between the arguments, element by element.
words <- c("one", "two", "three")
print(paste(words, collapse = "-"))
print(paste(words, 1:3, sep = "_"))Output:
[1] "one-two-three"
[1] "one_1" "two_2" "three_3"Text from input often has spaces around the separators. trimws() removes the spaces at the start and end of each element:
raw <- " apples , pears,plums "
items <- trimws(strsplit(raw, ",")[[1]])
print(items)
print(paste(rev(items), collapse = " | "))Output:
[1] "apples" "pears" "plums"
[1] "plums | pears | apples"strsplit() on a vector returns one list element per string, so each input line keeps its own pieces:
lines <- c("a,b", "c,d,e")
parts <- strsplit(lines, ",")
print(length(parts))
print(parts[[2]])Output:
[1] 2
[1] "c" "d" "e"Challenge
EasyComplete hashtags(line). The line holds tags separated by commas, possibly with spaces around them. Return one string with every tag prefixed by #, separated by single spaces: r, data ,stats becomes #r #data #stats.
The supplied code reads the line and prints the returned value.
Try it yourself
hashtags <- function(line) {
# Write your code here
line
}
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
cat(hashtags(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