Splitting Strings in R programming – strsplit() method
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
gfg < - "Geeks For Geeks"
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
gfg <- "Geeks9For2Geeks"
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
Share your thoughts in the comments
Please Login to comment...