How to Use letters(small case) in R

In R, ‘letters’ is a built-in constant that contains all the lowercase letters of the English alphabet. It is a vector of 26, each element being a single lowercase letter from ‘a’ to ‘z’.

This constant can be very helpful for generating labels, iterating over alphabetic sequences, or other tasks where you need a sequence of letters.

Syntax

letters

Visual representation

Visual representation of letters in R

Example 1: Basic usage

print(letters)

Output

[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"

You can see from the output that it returns lowercase character vectors of the alphabet.

To print specific letters in the sequence, say if you want only g, h & i. use the following code.

letters[7:9]

Output

[1] "g"  "h"  "i"

Example 2: Extracting characters

letters with head() function

To extract the first specific part of the object, use the “head()” function.

cat("First 6 characters from letters", "\n")

head(letters)

Output

First 6 characters from letters

[1] "a" "b" "c" "d" "e" "f"

And we get the first 10 uppercase letters in the output using the head() function.

Example 3: Extracting last specific parts

To extract the last specific parts of the object in R, use the tail() function.

cat("Last 10 characters from letters", "\n")

tail(letters, 10)

Output

Last 10 characters from letters
[1] "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"

Example 4: Using with the paste() function

To concate strings, use the paste() function. You can create a custom sequence of letters using the paste() function.

paste("millie_", letters, sep = "")

Output

[1] "millie_a" "millie_b" "millie_c" "millie_d" "millie_e" "millie_f"
[7] "millie_g" "millie_h" "millie_i" "millie_j" "millie_k" "millie_l"
[13] "millie_m" "millie_n" "millie_o" "millie_p" "millie_q" "millie_r"
[19] "millie_s" "millie_t" "millie_u" "millie_v" "millie_w" "millie_x"
[25] "millie_y" "millie_z"

Example 5: Looping over letters

for (letter in letters) {
  print(letter)
}

This loop will print each letter from ‘a’ to ‘z’.

Leave a Comment