How to Convert Strings to Lowercase in R (With Examples)


You can use the built-in tolower() function in R to convert strings to lowercase.

#convert string to lowercase
tolower(string_name)

The following examples show how to use this function in practice.

Example 1: Convert a Single String to Lowercase

The following code shows how to convert a single string to lowercase in R:

#create string
my_string <- 'THIS IS A SENTENCE WITH WORDS.'

#convert string to all lowercase
tolower(my_string)

[1] "this is a sentence with words."

Note that the tolower() function converts all characters in a string to lowercase

Example 2: Convert Each String in Column to Lowercase

The following code shows how to convert every string in a column of a data frame to lowercase:

#create data frame
df <- data.frame(team=c('Mavs', 'Nets', 'Spurs'),
                 points=c(99, 94, 85),
                 rebounds=c(31, 22, 29))

#view data frame
df

   team points rebounds
1  Mavs     99       31
2  Nets     94       22
3 Spurs     85       29

#convert team names to lowercase
df$team <- tolower(df$team)

#view updated data frame
df

   team points rebounds
1  mavs     99       31
2  nets     94       22
3 spurs     85       29

Example 3: Convert Strings in Multiple Columns to Lowercase

The following code shows how to convert strings in multiple columns of a data frame to lowercase:

#create data frame
df <- data.frame(team=c('Mavs', 'Nets', 'Spurs'),
                 conf=c('WEST', 'EAST', 'WEST'),
                 points=c(99, 94, 85))

#view data frame
df

   team conf points
1  Mavs WEST     99
2  Nets EAST     94
3 Spurs WEST     85

#convert team and conference to lowercase
df[c('team', 'conf')] <- sapply(df[c('team', 'conf')], function(x) tolower(x))

#view updated data frame
df
   team conf points
1  mavs west     99
2  nets east     94
3 spurs west     85

Additional Resources

The following tutorials explain how to perform other common tasks related to strings in R:

How to Use str_split in R
How to Use str_replace in R
How to Convert a Vector to String in R

Leave a Reply

Your email address will not be published.