R comes with two functions to convert strings to lowercase: tolower() and casefold() functions. The tolower() function in R converts a string to lowercase. This function takes a single argument, which is the string to be converted. In this guide, we will show how to convert string to lowercase in R.
Using tolower() Function to Convert String to Lowercase
In this method, we will use the tolower() function to convert string to lowercase in R.
Syntax
tolower(x)
Arguments
- x = string to be converted
Example 1: Using tolower() to Convert a Single String to Lowercase
# converting to lowercase tolower("HELLO WORLD!")
Output
[1] "hello world!"
Example 2: Using tolower() to Convert a Vector of Strings to Lowercase
# creating a vector x = c("HELLO", "WORLD!") # converting to lowercase tolower(x)
Output
[1] "hello" "world!"
Example 3: Using tolower() to Convert a Column of a Data Frame
# creating a data frame df = data.frame(x = c('Fruit', 'Vegetable', 'Dairy'), y = c('APPLE', 'POTATO','CURD')) df # converting column y to lowercase tolower(df$y)
Output
x y 1 Fruit APPLE 2 Vegetable POTATO 3 Dairy CURD [1] "apple" "potato" "curd"
In the above example, we used the $ sign to extract the column y from the data frame df.
Using casefold() Function to Convert String to Lowercase
Unlike the tolower() function, the casefold() function takes two arguments.
Syntax
casefold(x, upper=FALSE)
Arguments
- x = string to be converted
- upper = If TRUE then all characters are converted to uppercase. By default, it is FALSE, which converts the characters to lowercase.
Example 1: Using casefold() to Convert a Single String to Lowercase
# converting to lowercase casefold("JUSTICE LEAGUE", upper=FALSE)
Output
[1] "justice league"
Example 2: Using casefold() to Convert a Vector of Strings to Lowercase
# creating a vector x = c("JUSTICE", "LEAGUE") # converting to lowercase casefold(x,upper=FALSE)
Output
[1] "justice" "league"
Example 3: Using casefold() to Convert a Column of a Data Frame
# creating a data frame df = data.frame(x = c('Dominos', 'McDonalds', 'Starbucks'), y = c('PIZZA', 'BURGERS','COFFEE')) df # converting to lowercase tolower(df$y)
Output
x y 1 Dominos PIZZA 2 McDonalds BURGERS 3 Starbucks COFFEE [1] "pizza" "burgers" "coffee"