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.

Like we can use r string built-in functions -
  • to get 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 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 -

paste()

The paste() function concatenates several strings and returns the result in one long string.

Syntax

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!"

nchar()

The nchar() function finds the length of a string.

Syntax

nchar(string) 

Example

nchar("Hello World")

substr()

The substr() function 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)

strsplit()

The strsplit(x,split) splits a string x into an R list of substrings based on another string split in x.

Syntax

strsplit(x, split) 

Here, x is the sentance and split is the character vector used for splitting.

Example

strsplit("Hello Jorz, How are you?", "-")




toupper()

The toupper function converts all strings to uppercase.

Syntax

toupper(string) 

Example

toupper("Hello Jorz, How are you?")

tolower()

The tolower function converts all strings to lowercase.

Syntax

tolower(string) 

Example

tolower("Hello Jorz, How are you?")