R Strings
Strings in R are used to represent and manipulate text. They are enclosed in double quotes (") or single quotes ('). R provides several functions for string operations, such as concatenation, substring extraction, and more.
Key Topics
1. String Creation and Manipulation
Strings in R can be created using double or single quotes. The paste() and paste0() functions are used for concatenating strings, while substr() can extract substrings.
# Creating and manipulating strings
name <- "Rudra"
greeting <- "Hello, "
full_greeting <- paste(greeting, name, "!") # Concatenate with space
substring <- substr(full_greeting, 1, 5) # Extract substring
print(full_greeting)
print(substring)
Output:
[1] "Hello"
Code Explanation: The paste() function concatenates greeting, name, and "!" with spaces. The substr() function extracts the substring from position 1 to 5, resulting in "Hello".
2. Escape Characters
Escape characters are used to represent special characters in strings. They start with a backslash (\) followed by a character. Common escape characters in R include:
| Escape Character | Description |
|---|---|
\n | New line |
\t | Tab space |
\\ | Backslash |
\" | Double quote |
\' | Single quote |
# Using escape characters
escaped_string <- "R says \"Hello\" to everyone!\nWelcome to R programming."
print(escaped_string)
Output:
Code Explanation: The string includes escape characters: \" to include double quotes within the string and \n to add a new line. When printed, these escape characters are interpreted accordingly, creating formatted text.
Key Takeaways
- Strings in R can be enclosed in either single or double quotes.
- The
paste()andpaste0()functions are used for concatenating strings. - Escape characters are used to represent special characters within strings.