How to use string literals in R

Overview

A string is simply used to store text. A string is always written in single quotation ('') marks or double quotation marks(""). For example, 'Hello world', "Hello World", etc.

Note: A string of the same characters inserted in a single quotation mark is the same as when it is inserted in a double quotation mark. For example, the "Hello World" string is the same as 'Hello world'.

Code

# the string variables below are both the same
"Hello World"
'Hello World'

How to assign a string to a variable

In the R language, we can use the <- operator to assign a string to a variable. The operator comes in between the variable and the string.

Code

# assigning strings to variables
string1 <- 'Hello World'
string2 <- 'Hope you are good?'
# to print the variables
string1
string2

How to create a multiline string

Multiline strings are a simple way to split a long string into different lines in your code. We use the cat() function to create multiline strings in R. To use the cat() function, all we need to do is pass the multiline string variable as a parameter.

Code

# a multiline string variable
string1 = 'In the land of myth and in times of magic,
the destiny of a great kingdom
rests on the shoulders of a young man,
his name,
Merlin.'
# using the cat() function to create the multiline string
cat(string1)

Note: If we don’t use the cat() function, R will add a \n at the end of each line break. This is because \n is an escape character and n means a new line.

Code

# a multiline string variables
string1 = 'In the land of myth and in times of magic,
the destiny of a great kingdom
rests on the shoulders of a young man,
his name,
Merlin.'
# without using the cat() function
string1

Free Resources