Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R split on delimiter (split) keep the delimiter (split)

Tags:

In R you can use the strsplit function to split a vector on a delimiter(split) as follows:

x <- "What is this?  It's an onion.  What! That's| Well Crazy." unlist(strsplit(x, "[\\?\\.\\!\\|]", perl=TRUE))  ## [1] "What is this"    "  It's an onion" "  What"          " That's"         ## [5] " Well Crazy" 

I'd like to keep the delimiter(split) using R. So the desired output would be:

## [1] "What is this?"    "  It's an onion." "  What!"          " That's|"         ## [5] " Well Crazy." 
like image 611
Tyler Rinker Avatar asked Feb 01 '14 01:02

Tyler Rinker


People also ask

How do I separate delimiter in R?

Use str_split to Split String by Delimiter in R Alternatively, the str_split function can also be utilized to split string by delimiter. str_split is part of the stringr package. It almost works in the same way as strsplit does, except that str_split also takes regular expressions as the pattern.

How do you split from delimiter?

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.

Does Split use regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.


1 Answers

You can use "(?<=DELIMITERS)":

unlist(strsplit(x, "(?<=[?.!|])", perl=TRUE))  ## [1] "What is this?"    "  It's an onion." "  What!"          " That's|"         ## [5] " Well Crazy. 
like image 73
Tyler Rinker Avatar answered Sep 27 '22 16:09

Tyler Rinker