R String Functions
String Functions
In the Strings chapter, you used nchar(), grepl() and paste().
R has many more built-in functions for working with text. This chapter shows the ones you will use most.
Upper and Lower Case
The toupper() function returns the string in upper case, and tolower() returns it in lower case:
Example
txt <- "Hello World!"
toupper(txt)
tolower(txt)
Try it Yourself »
Get Part of a String
Use the substr() function to get some of the characters in a string.
The first argument is the string, the second is the start position, and the third is the end position:
Example
txt <- "Hello World!"
substr(txt, 1, 5)
Try it Yourself »
Note: The first character has position 1, just like the first item in a vector. Both the start and the end position are included.
Replace Text
The sub() function replaces the first match in a string, and gsub() replaces all matches:
Example
txt <- "one apple, one banana"
sub("one", "two", txt)
gsub("one", "two", txt)
Try it Yourself »
The first argument is the text to look for, the second is the new text, and the third is the string.
Remove Spaces
Text from users or files often has extra spaces at the start or end. Use trimws() to remove them:
Example
txt <- " Hello World! "
trimws(txt)
Try it Yourself »
Split a String
The strsplit() function splits a string into parts, at each place where it finds the separator:
Example
fruits <- "apple,banana,cherry"
strsplit(fruits, ",")
Try it Yourself »
The result is a list. You will learn more about lists in the R Lists chapter.
Join Strings Without Spaces
The paste() function puts a space between the parts. Use paste0() to join them with no space at all, or use the sep argument to choose your own separator:
Example
paste0("Hello", "World")
paste("Hello", "World", sep = "-")
Try it Yourself »
Insert Values with sprintf()
The sprintf() function puts values into a string. Each % code in the text is replaced by the next value:
Example
name <- "John"
age <- 40
sprintf("%s is %d years old", name, age)
Try it Yourself »
The most common codes are:
%s- a string (text)%d- a whole number%.2f- a number with 2 decimals
Use %.2f to show a price with two decimals:
Example
price <- 9.5
sprintf("The price is %.2f dollars", price)
Try it Yourself »
String Functions Overview
| Function | Description |
|---|---|
| nchar() | Returns the number of characters in a string |
| toupper() | Converts a string to upper case |
| tolower() | Converts a string to lower case |
| substr() | Returns part of a string |
| grepl() | Checks if a string contains some text (TRUE or FALSE) |
| sub() | Replaces the first match |
| gsub() | Replaces all matches |
| trimws() | Removes spaces at the start and end of a string |
| strsplit() | Splits a string into parts |
| paste() | Joins strings with a space between them |
| paste0() | Joins strings with no space between them |
| sprintf() | Inserts values into a string |