LETTERS in R: The Complete Guide

R has several built-in constants like letters, LETTERS, or month.abb, etc. A constant in a programming language is a value that cannot be changed by the program during its execution.

LETTERS in R

To create a sequential uppercase alphabet in R, use the LETTERS constant.  The LETTERS is a character constant in R that generates an uppercase alphabet, and you can use it with different functions to extract the result as per your requirement.

Syntax

LETTERS

Example

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 uppercase character vectors of the alphabet.

To print specific letters in the sequence, say if you want only J, K & L. use the following code.

LETTERS[10:12]

Output

[1] "J"  "K"  "L"

Extract characters from LETTERS using head()

To get the first specific part of the object in R, use the head() function. The head() function returns the first part of a vectormatrix, table, data frame, or function.

In this example, we will get the first specific character vectors from LETTERS.

cat("First 10 characters from LETTERS", "\n")
head(LETTERS, 10)

Output

First 10 characters from LETTERS
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J"

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

Using tail() function

To get the last parts of the object in R, use the tail() function. The tail() function returns the last part of a vector, matrix, table, data frame, or 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"

Using LETTERS with paste() function

To concat strings in R, use the paste() function. The paste() method converts its input arguments to character strings and concatenates them.

You can create a custom sequence of LETTERS in R using the paste() function. For example, you can create a sequence like,

Millie_A Millie_B Millie_C ... Millie_Z

See the following code.

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"

That is it for LETTERS constant in R.

Leave a Comment