Strings are a collection of various characters in the R language. These characters are enclosed in single or double quotation marks. Strings can also contain numbers, special characters, or spaces.
We must consider some rules when we construct strings in R:
This example demonstrates the rules mentioned above.
# Properties of String Data Structure in Rstr1 <- 'valid string 1'print(str1)str2 <- "another valid string"print(str2)str3 <- " we can also ' in double quotes "print(str3)str4 <- ' example of "valid" strings 'print(str4)
Now, let’s discuss an example of some strings that are not allowed.
A single quote is not allowed in line 4. A double quote within a double quote also produces Error: unexpected
in line 7.
i1 <- 'not allowed"print(i1)i2 <- 'invalid' string'print(i2)i3 <- "it is also" not allowed"print(i3)
stringr
?Stringr
is a package in the R language that is used to perform fast manipulations on strings. Stringr
contains all the relevant functions to perform string manipulation. Basically, strings are the combinations of various characters, and stringr
is a package for performing manipulations on these character sequences.
Stringr
package examples:
Every function in this package will start with str_
.
You can get the size of a string or list of strings with the str_length()
method. This method is equivalent to nchar()
, which also returns the string’s length after the R.3.3.0 update.
str_length("abc")
str_length(c("strings", "length"))
str_c()
helps to combine multiple strings; str_c()
takes a vector of strings and collapses characters, i.e., comma. It returns the condensed string.
str_c(x, collapse = ", ")
str_c("what", "are", "strings?")
You can retrieve the part of strings through this function. We have to initialize the start and end when using this function.
a <- c("Black", "White", "Green")
str_sub(a,1,3)