R toupper() and tolower() Functions - Case Conversion
The R toupper() function converts strings to uppercase, and tolower() converts them to lowercase.
During data cleaning and text preprocessing, unifying case is a common operation.
The syntax of these two functions is as follows:
toupper(x)
tolower(x)
Parameter Description:
-
x An input string or character vector.
Example
text
<-
"Hello RUNOOB World"
Convert to uppercase
(
toupper
(
text
)
)
Convert to lowercase
(
tolower
(
text
)
)
Case conversion in a vector
words
<-
c
(
"Apple"
,
"Banana"
,
"Cherry"
)
(
"All uppercase:"
)
(
toupper
(
words
)
)
(
"All lowercase:"
)
(
tolower
(
words
)
)
The output of the code above is:
[1] "HELLO RUNOOB WORLD"
[1] "hello runoob world"
[1] "全部大写:"
[1] "APPLE" "BANANA" "CHERRY"
[1] "全部小写:"
[1] "apple" "banana" "cherry"
Case conversion is often used for standardization before data matching:
Example
Compare after unifying to lowercase
user_input
<-
"RunOOb"
standard
<-
tolower
(
user_input
)
if
(
standard
==
"runoob"
)
{
(
"Match successful!"
)
}
Capitalize the first letter (custom function)
capitalize
<-
function
(
x
)
{
paste0
(
toupper
(
substr
(
x,
1
,
1
)
)
,
tolower
(
substr
(
x,
2
,
nchar
(
x
)
)
)
)
}
(
capitalize
(
c
(
"hello"
,
"WORLD"
,
"rUnoob"
)
)
)
The output of the code above is:
[1] "匹配成功!"
[1] "Hello" "World" "Runoob"
R Language Examples