What are the toupper(), tolower(), and casefold() functions in R?
Overview
In R, the toupper() function is used to convert string characters to upper case, whereas, the tolower() function is used to convert string characters to lower case.
The casefold() function, on the other hand, is used to convert string characters to upper or lower case, depending on the value of the upper parameter assigned to it.
Syntax
| Syntax | Parameter value | Return value |
|---|---|---|
| toupper(x) | x: The string object |
A string object in upper case |
| tolower(x) | x: The string object |
A string object in lower case |
| casefold(x, upper) | x: The string object |
A string object in lower case or upper case |
upper: The Boolean value for case conversion |
Example 1
# creating a string objectthisstring <- c("I love R language")# implementing the toupper() functionmystring1 <- toupper(thisstring)# implementing the tolower() functionmystring2 <- tolower(thisstring)# implementing the casefold() function for UPPER CASEmystring3 <- casefold(thisstring, upper=TRUE)# printing the stringsmystring1mystring2mystring3
Explanation
- Line 2: We create a string object or variable
thisstring. - Line 5: We implement the
toupper()function on the string variablethisstring. We assign the result to another variablemystring1. - Line 8: We implement the
tolower()function on the string variablethisstring. We assign the result to another variablemystring2. - Line 11: We implement the
casefold()function on the string variablethisstring. We assign the result to another variablemystring3. - Line 14: We print the
mystring1variable. - Line 15: We print the
mystring2variable. - Line 16: We print the
mystring3variable.
Example 2
# creating a string objectsthisstring <- c("I love R language")anotherstring <- c("It is so easy to LEARN!")# implementing the toupper() functionmystring1 <- toupper(c(thisstring, anotherstring))# implementing the tolower() functionmystring2 <- tolower(c(thisstring, anotherstring))# implementing the ccasefold() function for lower casemystring3 <- casefold(c(thisstring, anotherstring), upper=FALSE)# printing the stringsmystring1mystring2mystring3
Explanation
- Line 2 and 3: We create two string variables,
thisstringandanotherstring. - Line 6: We implement the
toupper()function on the concatenation of both string variablesthisstringandanotherstring. We assign the result to another variablemystring1. - Line 9: We implement the
tolower()function on the concatenation of both string variablesthisstringandanotherstring. We assign the result to another variablemystring2. - Line 12: We implement the
casefold()function on the concatenation of both string variablesthisstringandanotherstring. We assign the result to another variablemystring3. - Line 15: We print the variable
mystring1. - Line 16: We print the variable
mystring2. - Line 17: We print the variable
mystring3.