R toupper() and tolower() functions - Case conversion
R toupper() function is used to convert strings to uppercase, tolower() to lowercase.
In data cleaning and text preprocessing, normalizing case is a common operation.
The syntax of these two functions is as follows:
toupper(x) tolower(x)
Parameter description:
xInput string or string vector.
Example
text <- "Hello EXAMPLE World"
# Convert to uppercase
print(toupper(text))
# Convert to lowercase
print(tolower(text))
# Case conversion in vectors
words <- c("Apple", "Banana", "Cherry")
print("All uppercase:")
print(toupper(words))
print("All lowercase:")
print(tolower(words))
# Convert to uppercase
print(toupper(text))
# Convert to lowercase
print(tolower(text))
# Case conversion in vectors
words <- c("Apple", "Banana", "Cherry")
print("All uppercase:")
print(toupper(words))
print("All lowercase:")
print(tolower(words))
The output of executing the above code is:
[1] "HELLO EXAMPLE WORLD" [1] "hello example 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 <- "example"
standard <- tolower(user_input)
if (standard == "example") {
print("Match successful!")
}
# Capitalize first letter (custom function)
capitalize <- function(x) {
paste0(toupper(substr(x, 1, 1)),
tolower(substr(x, 2, nchar(x))))
}
print(capitalize(c("hello", "WORLD", "example")))
user_input <- "example"
standard <- tolower(user_input)
if (standard == "example") {
print("Match successful!")
}
# Capitalize first letter (custom function)
capitalize <- function(x) {
paste0(toupper(substr(x, 1, 1)),
tolower(substr(x, 2, nchar(x))))
}
print(capitalize(c("hello", "WORLD", "example")))
The output of executing the above code is:
[1] "匹配成功!" [1] "Hello" "World" "Example"Other extensions
R language examples