In this tutorial, you will learn about R strings. In R, a variable defined as a string can hold values of any data type such as numeric, character, or any special symbols, etc, and are generally one-dimensional array-like structures (1D-array ) with the capability of holding single and multiple values. There are various functions available in R to manipulate strings such as tolower() ,toupper(),nchar(),substr() etc.In this tutorial under the string manipulations section, you will explore in detail regarding these functions.
An R string is a collection of words or a single word or can be any numeric values enclosed within a single quote ‘ ‘ or double quotes “ “.A string in R is valid only if the values begin with a single or double quote and end up with corresponding closing quotes.
Let us understand this with a simple R program. Consider the below-given program to print two strings mentioned by variables str1 and str2.
str1 <- "Welcome to Learn eTutorials"
print(str1)
str2 <- 'you are learning R tutorials'
print(str2)
The output after successful execution of these codes are
[1] "Welcome to Learn eTutorials" [1] "you are learning R tutorials"
In R a string with double quotes consisting of another double quote inside the same string is not allowed whereas double quotes with embedded single quotes inside the same string is admitted.
The same is not applicable in the case of single quotes enclosed in a single quotes string within it while the enclosing of strings with double quotes inside a single-quoted string is allowed. Let us make it clear without any confusion given below table.
Cases | Example (Input) | Output | Validity |
---|---|---|---|
1. String with double quotes inside a single quotes | str3 <- ' R tutorials "String" ' | [1] " R tutorials \"String\" " | valid |
2. String with single quotes inside a double quotes | str4 <- "R tutorials 'String4' " | [1] "R tutorials 'String4' " | valid |
3. String with double quotes with another double quote within it | str5 <- "R tutorials "String5" " | Error: unexpected symbol in "str5 <- "R tutorials "String5" | invalid |
4. String with single quotes with another single quote within it. | str6<- 'R tutorials 'String6' ' | Error: unexpected symbol in "str6<- 'R tutorials 'String6" | invalid |
Inferences from table
These inferences from the table we derived from the rules that need to be followed while constructing strings in the R programming language.
Note: Single- quoted strings are not allowed to have another single quotes inside it.Similary double –quoted strings are not allowed to have another double quotes inside it.