Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

r
communitycreator

How to use string literals in R

Onyejiaku Theophilus Chidalu

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'
Strings enclosed in single or double quotation marks are the same

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
Assigning a string to a variable

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)
Using the cat() function to create a multiline string

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
Without using the cat() function

RELATED TAGS

r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring