Home » How to Use LETTERS in R (With Examples)

How to Use LETTERS in R (With Examples)

by Tutor Aspire

You can use the LETTERS constant in R to access letters from the alphabet.

The following examples show the most common ways to use the LETTERS constant in practice.

Example 1: Generate Uppercase Letters

If you simply type LETTERS, every letter in the alphabet will be displayed in uppercase:

#display every letter in alphabet in uppercase
LETTERS

 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"

To access a specific subset of letters in the alphabet, you can use the following syntax:

#display letters in positions 4 through 8 in uppercase
LETTERS[4:8]

[1] "D" "E" "F" "G" "H"

Notice that only the letters in positions 4 through 8 are returned.

Example 2: Generate Lowercase Letters

If you type letters, every letter in the alphabet will be displayed in lowercase:

#display every letter in alphabet in lowercase
letters

 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"

To access a specific subset of letters in the alphabet, you can use the following syntax:

#display letters in positions 4 through 8 in lowercase
letters[4:8]

[1] "d" "e" "f" "g" "h"

Notice that only the letters in positions 4 through 8 are returned.

Example 3: Generate Random Letters

You can randomly select one letter from the alphabet by using the sample() function:

#select random uppercase letter from alphabet
sample(LETTERS, 1)

[1] "K"

You can also generate a random sequence of letters by using the paste() function along with the sample() function:

#generate random sequence of 10 letters in uppercase
paste(sample(LETTERS, 10, replace=TRUE), collapse="")

[1] "BPTISQSOJI"

Example 4: Concatenate Letters with Other Strings

You can also use the paste() function to concatenate each letter in the alphabet with another string:

#display each letter with "letter_" in front
paste("letter_", letters, sep="")

 [1] "letter_a" "letter_b" "letter_c" "letter_d" "letter_e" "letter_f"
 [7] "letter_g" "letter_h" "letter_i" "letter_j" "letter_k" "letter_l"
[13] "letter_m" "letter_n" "letter_o" "letter_p" "letter_q" "letter_r"
[19] "letter_s" "letter_t" "letter_u" "letter_v" "letter_w" "letter_x"
[25] "letter_y" "letter_z"

Notice that “letter_” has been concatenated to the beginning of each letter.

Additional Resources

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

How to Remove Last Character from String in R
How to Find Location of Character in a String in R
How to Select Columns Containing a Specific String in R

You may also like