R Strings
A string is an arrangement of characters. R has a good combination of built-in functions for string handling and easily manipulation of strings.
As we can use the R string built-in functions -
- to get the length of string.
- to reverse a string.
- to convert the string in lowercase or uppercase.
- to split a string.
- to replace some part or character of a string.
- to trim white spaces from the beginning and end of the string.
- to convert the string in encoded form.
- to get position of a substring or a character in a string.
Some examples of R String
str1 <- 'The biggest animal in the world is "Blue Whale".'
print(str1)
str2 <- "The biggest bird in the world is 'Ostrich'."
print(str2)
Some of the mostly used built-in functions are -
R paste() function
The paste() function of R concatenates several strings and returns the result in one long string.
Syntax of paste()
paste(str1, str2, ... ,strN, sep="", collapse = NULL)
Here, sep and collapse are optional fields. The sep represents the separator symbol and the collapse is used to eliminate the space between two strings.
paste("Hello","World")
[1] "Hello World"
> paste("Hello","World",sep="")
[1] "HelloPole"
> paste("Hello","World",sep=".")
[1] "Hello.World"
> paste("Hello",",","World","!")
[1] "Hello,World!"
R nchar() function
The nchar() function of R finds the length of a string.
Syntax of nchar()
nchar(string)
Example
nchar("Hello World")
R substr() function
The substr() function of R returns a portion of a string. This function takes start and stop positions of the string characters range.
Syntax
substr(string, start=n1, stop=n2)
Example
substr("Hello World", 3, 8)
R strsplit() function
The strsplit(x,split) function of R splits a string x into an R list of substrings based on another string split in x.
Syntax of strsplit()
strsplit(x, split)
Here, x is the sentence and split is the character vector used for splitting.
Example
strsplit("Hello Jorz, How are you?", "-")
R toupper() function
The toupper function of R converts all strings to uppercase.
Syntax of toupper()
toupper(string)
Example
toupper("Hello Jorz, How are you?")
R tolower() function
The tolower function of R converts all strings to lowercase.
Syntax of tolower()
tolower(string)
Example
tolower("Hello Jorz, How are you?")