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'
.
# the string variables below are both the same"Hello World"'Hello World'
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.
# assigning strings to variablesstring1 <- 'Hello World'string2 <- 'Hope you are good?'# to print the variablesstring1string2
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.
# a multiline string variablestring1 = 'In the land of myth and in times of magic,the destiny of a great kingdomrests on the shoulders of a young man,his name,Merlin.'# using the cat() function to create the multiline stringcat(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 andn
means a new line.
# a multiline string variablesstring1 = 'In the land of myth and in times of magic,the destiny of a great kingdomrests on the shoulders of a young man,his name,Merlin.'# without using the cat() functionstring1