letters in R with Example

R has several built-in constants like letters, pi, letters, LETTERS, 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 lowercase alphabet in R, use the letters constant.  The letters is a character constant in R that generates a lowercase 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 lowercase character vectors of the alphabet.

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

letters[7:9]

Output

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

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.

Extract characters from LETTERS using tail()

To get the last specific parts of the object in R, use the tail() function. The tail() function returns the last part of a vectormatrix, 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 concate 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_a 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