R Tutorials
R Data Structures
R Graphics
R Statistics
R Examples
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'
:
"hello"
'hello'
The flexibility of the character unit is done with a variable followed by <-
operator and character unit:
str <- "Hello"
str # print the value of str
You can assign a multi-line string to variables such as:
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
str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do
eiusmod tempor incididunt
ut labore et dolore magna aliqua."
cat(str)
There are many useful rope functions in R.
For example, to find the number of characters in a character unit, use the nchar()
function:
str <- "Hello World!"
nchar(str)
Use the grepl()
function to check if a character or letter sequence exists in a character unit:
str <- "Hello World!"
grepl("H", str)
grepl("Hello",
str)
grepl("X",
str)
Use the paste()
function to connect / connect two wires:
str1 <- "Hello"
str2 <- "World"
paste(str1, str2)
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:
str <- "We are the so-called "Vikings", from the north."
str
To fix this issue, use the escape letter \"
:
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 |