How to use LETTERS in R?

R lets you use letters as variables to store values. To do this, you can assign a letter to a value by typing the letter followed by an equals sign and then the value. For example, if you wanted to assign the value of 4 to the letter a, you would type a = 4. You can then use the letter a to access the value of 4 whenever you need it.


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"

#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.

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

x