R Strings


String Literals

Character, or strings, is used to store text. The character unit is surrounded by either a single quotation mark, or two quotation marks:

"hello" is the same as 'hello':

Example
"hello"
'hello'


Assign a String to a Variable

The flexibility of the character unit is done with a variable followed by <- operator and character unit:

Example
str <- "Hello"
str # print the value of str


Multiline Strings

You can assign a multi-line string to variables such as:

Example
str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."


str # print the value of str

However, note that R will add "\ n" at the end of each line break. This is called the escape letter, and the n letter indicates a new line.

If you want the line break to be aligned with the code, use the cat() function

Example
str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."


cat(str)


String Length

There are many useful rope functions in R.

For example, to find the number of characters in a character unit, use the nchar() function:

Example
str <- "Hello World!"

nchar(str)


Check a String

Use the grepl() function to check if a character or letter sequence exists in a character unit:

Example
str <- "Hello World!"

grepl("H", str)
grepl("Hello", str)
grepl("X", str)


Combine Two Strings

Use the paste() function to connect / connect two wires:

Example
str1 <- "Hello"
str2 <- "World"

paste(str1, str2)


Escape Characters

To insert illegal characters into a character unit, you must use the escape letter.

The escape character is the backslash \ followed by the character you want to insert.

An example of an illegal character is two quotations within a character unit surrounded by two quotations:

Example
str <- "We are the so-called "Vikings", from the north."

str

To fix this issue, use the escape letter \":

Example

The escape character allows you to use double quotes when you normally would not be allowed:

str <- "We are the so-called \"Vikings\", from the north."

str
cat(str)

Other escape characters in R:

Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace