R String Functions
A string function changes text or picks part of it out. Each call returns a new string.
Changing case
toupper changes a word to uppercase letters. tolower changes a word to lowercase letters.
print(toupper("hello"))
print(tolower("HELLO"))Picking out part of a string
substr picks out five characters from the start of the string. The second call picks out the last five characters.
print(substr("Hello World", 1, 5))
print(substr("Hello World", 7, 11))Case and length together
word holds a short text value. toupper changes it to uppercase and nchar counts its letters.
word <- "program"
print(toupper(word))
print(nchar(word))Example
name <- "gRaCe"
tidy <- tolower(name)
code_name <- toupper(substr(tidy, 1, 3))
print(tidy)
print(code_name)Key points
- toupper changes every letter in a string to uppercase.
- tolower changes every letter in a string to lowercase.
- substr picks out part of a string.
- The first value in substr is the string to cut from.
- The next two values in substr give the start and stop positions.
- Counting for substr starts at 1.
- The original string stays unchanged after a call.
In this example, tolower first tidies the messy name to grace. substr then takes the first three letters. toupper turns that short code into GRA.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does print(substr("Hello World", 1, 5)) show?