Any value coded within a pair of single quote (' ') and double quotes (" ") in R programming is termed as a 'string'. On the inside, R stores all the strings within double quotes, even if you use single quotes to create them. In this chapter you will learn about the basic concepts that R provides on Strings.

What are Strings in R programming?

Text data gets stored in character vectors or may be character arrays. This is significant to keep in mind that every element of a character vector designates a whole string, rather than just an individual character. In R programming, a "string" is a casual term which is used because 'element of a character vector' is quite a tasteful term.

Constructing and Printing Strings

As you know, character vectors are required to create using the c function. You can use both single and double quotes around any string, as long as they match although double quotes are considered more customary. Here is an simple example of how to use them:

c (
"Programmer must imply double quotes in maximum case",
'Single quotes are used for including " within the string'
)

The output goes something like this:

# In most of the cases, you have to use double quote"
# [2] "Single quotes are used for including "within a string"

There is another function name 'paste' function which unites strings mutually. Each vector passed to this has its constituents recycled to reach the length of the longest possible input and then strings get concatenated including a space separating them.

You can alter the separator by putting an argument called 'sep', or implement the associated function 'paste0' to have no separator.The example is shown below with output:

The 'toString' Function

The toString function is a deviation of paste which is useful while printing vectors. This divides each element using a comma and a space. It can limit how much you want to print. Here is an example showing its use:

g <- (1:7) ^ 2
toString (g)
# [1] "1, 4, 9, 16, 25, 36, 49"

Formatting Numbers

There are various functions for formatting numbers. formatC uses C-style formatting terms which allows you to identify fixed or scientific formatting, the amount of decimal places, and the width of the output. Whatever the options is, the input must have to be one of the numeric types (which can also be arrays) and the output has to be character vector or array:

pow <- 1:3
(powr_of_e <- exp (pow))
## [1] 2.718 7.389 20.086

Changing the case in R

R allows programmers to convert the case of the letters / strings used within a program using two pre defined functions. These are:

toupper() &
tolower() functions

These functions alter the case of characters of a string. The fundamental syntax for toupper() & tolower() function is: