Open In App

Splitting Strings in R programming – strsplit() method

Improve
Improve
Like Article
Like
Save
Share
Report

strsplit() method in R Programming Language is used to split the string by using a delimiter.

strsplit() Syntax:

Syntax: strsplit(string, split, fixed)

Parameters:

  • string: Input vector or string.
  • split: It is a character of string to being split.
  • fixed: Match the split or use the regular expression.

Return: Returns the list of words or sentences after split. 

Splitting Strings in R language Example

Example 1: Using strsplit() function with delimiter

Here, we are using strsplit() along with delimiter, delimiter is a character of an existing string to being removed from the string and display out.

R




# R program to split a string
 
# Given String
gfg < - "Geeks For Geeks"
 
# Using strsplit() method
answer < - strsplit(gfg, " ")
 
print(answer)


Output:

[1] "Geeks" "For"   "Geeks"

Example 2: strsplit() function with Regular Expression delimiter

Here, we are using regular expressions in delimiter to split the string.

R




# R program to split a string
 
# Given String
gfg <- "Geeks9For2Geeks"
 
# Using strsplit() method
answer <- strsplit(gfg, split = "[0-9]+")
 
print(answer)


Output:

[1] "Geeks" "For"   "Geeks"

Example 3: Splitting the dates using strsplit() function in R

We can also manipulate with date using strsplit(), only we need to understand the date formatting, for example in this date( 2-07-2020) following the same pattern (-), so we can remove them using delimiter along with “-“. 

R




string_date<-c("2-07-2020","5-07-2020","6-07-2020",
               "7-07-2020","8-07-2020")
result<-strsplit(string_date,split = "-")
print(result)


Output:

[[1]]
[1] "2"    "07"   "2020"

[[2]]
[1] "5"    "07"   "2020"

[[3]]
[1] "6"    "07"   "2020"

[[4]]
[1] "7"    "07"   "2020"

[[5]]
[1] "8"    "07"   "2020"


Last Updated : 11 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads