R – Split String

In this tutorial, we will learn how to split a string by delimiter in R programming Language.

To split a string in R programming, use strsplit() function.

The syntax of strsplit() function that is used to split a string by delimiter is

strsplit(x, split, fixed = FALSE, perl = FALSE, useBytes = FALSE)

where

ParameterDescription
x[Mandator] A character vector.
split[Mandator] A character vector which are used as delimiter/separator. A regular expression can also be given.
fixed[Optional] If TRUE, then the split is exactly matched.
perl[Optional] If TRUE, Perl-compatible regexps should be used.
useBytes[Optional] If TRUE, then matching is done byte by byte instead of character by character.

Examples

Split String by Space Delimiter

In this example, we take a string in x, and split it by a single space as split delimiter/separator.

Example.R

x <- "apple banana cherry"
split <- " "
result <- strsplit( x, split )
print( result )

Output

[[1]]
[1] "apple"  "banana" "cherry"

Split String by a Delimiter String

In this example, we take a string in x, and split it by the delimiter/separator "xyz".

Example.R

x <- "applexyzbananaxyzcherry"
split <- "xyz"
result <- strsplit( x, split )
print( result )

Output

[[1]]
[1] "apple"  "banana" "cherry"

Split String by a Regular Expression

We can provide a regular expression for split parameter to strsplit() function.

In the following example, we split the string x, with any digit or sequence of digits as separator. The regular expression to match one or more digits is "\\d+".

Example.R

x <- "apple58banana4cherry"
split <- "\\d+"
result <- strsplit( x, split )
print( result )

Output

[[1]]
[1] "apple"  "banana" "cherry"
ADVERTISEMENT

Conclusion

In this R Tutorial, we learned how to split a string or vector of characters using strsplit() function, with the help of example programs.