Convert List to Lowercase or Uppercase in R (2 Examples)
In this article you’ll learn how to set the character strings in a list to lowercase or uppercase in R.
The article consists of these content blocks:
Here’s the step-by-step process…
Example Data
The following data will be used as basement for this R tutorial:
my_list <- list(LETTERS[1:5], # Create example list c("Foo", "Bar"), "AaAaAaA") my_list # Print example list # [[1]] # [1] "A" "B" "C" "D" "E" # # [[2]] # [1] "Foo" "Bar" # # [[3]] # [1] "AaAaAaA" #
As you can see based on the previous output of the RStudio console, the exemplifying list contains three list elements. Each of these list elements consists of character string vectors with majuscule and minuscule representations.
Example 1: Convert All Characters in List to Lowercase
The following syntax shows how to switch the case of all characters in our list to lowercase.
For this, we can use the lapply and tolower functions as shown below:
my_list_lower <- lapply(my_list, tolower) # Apply tolower() function my_list_lower # Print lowercase list # [[1]] # [1] "a" "b" "c" "d" "e" # # [[2]] # [1] "foo" "bar" # # [[3]] # [1] "aaaaaaa" #
Have a look at the previous output of the RStudio console. It shows that all characters in our list have been set to lowercase.
Example 2: Convert All Characters in List to Uppercase
In Example 2, I’ll explain how to convert the letters in a list to capitals.
Similar to the syntax that we have used in Example 1, we can use the lapply and toupper functions to convert all characters to uppercase:
my_list_upper <- lapply(my_list, toupper) # Apply toupper() function my_list_upper # Print uppercase list # [[1]] # [1] "A" "B" "C" "D" "E" # # [[2]] # [1] "FOO" "BAR" # # [[3]] # [1] "AAAAAAA" #
The previous output shows that we have created a new list where all letters are set to uppercase.
Video & Further Resources
I have recently released a video on my YouTube channel, which explains the R programming syntax of this tutorial. You can find the video below:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Also, you may have a look at the other tutorials on this website:
- tolower, toupper, casefold & chartr Functions
- Capitalize First Letter of Each Word in Character String
- Convert All Character String Variables in Data Frame to Uppercase
- R Programming Tutorials
Summary: This article has shown how to change the letter case of characters in a list in the R programming language. In case you have additional comments and/or questions, tell me about it in the comments.
Statistics Globe Newsletter