String Split with strsplit function in R

strsplit function in R is used to split the string into substrings with the specified delimiter. So that the resultant substrings are separated by a delimiter.

Syntax for strsplit function in R:

strsplit() function in R takes two arguments, the string and the delimiter of the substrings

strsplit(string, delimiter)

The delimiter can be either a simple string or a regular expression

Example for strsplit() function in R:

## strsplit function in R with space delimiter

mysentence<- "india won the icc worldcup on 2011"
strsplit(mysentence," ")

In the above example the string is split into substring with space delimiter so the output will be

[[1]]
[1] “india”    “won”      “the”      “icc”      “worldcup” “on”       “2011”

 

## strsplit function in R with / as delimiter

path <- "home/lincon/data/output.csv"
strsplit(path,"/")

In the above example the string is split into substring with “/” delimiter so the output will be

[[1]]
[1] “home”       “lincon”     “data”       “output.csv”

 

Example for strsplit() function in R with Regular expression:

## strsplit() function in R with regular expression

mysentence <- "mike19sana17are1siblings"
strsplit(mysentence, "[0-9]+")

In the above example we have replaced all the numbers with space, with the help of regular expression “[0-9]+” so the output will be

[[1]]
[1] “mike”     “sana”     “are”      “siblings”

previous small strsplit function in r                                                                                                           next small strsplit function in r

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts