ag14
ag14

Reputation: 867

strsplit does not split for all elements of character vector provided to parameter "split"

The R documentation for the strsplit function states for parameter split that "If split has length greater than 1, it is re-cycled along x."

I take it to mean that if I use the following code

strsplit(x = "Whatever will be will be", split = c("ever", "be"))

..., I will get x split into "What" and "will" and "will be". This does not happen. The output is "What" and "will be will be".

Am I misinterpreting the documentation? Also, how can I get the result I desire?

Upvotes: 1

Views: 90

Answers (2)

iod
iod

Reputation: 7592

The split is recycled across elements of x, so that the first element of split is applied to the first element of x, the second to the second, etc. So, for example:

strsplit(x = c("Whatever will be will be", "Whatever will be will be"), split = c("ever", "be"))
[[1]]
[1] "What"             " will be will be"

[[2]]
[1] "Whatever will " " will "

Upvotes: 1

bobbel
bobbel

Reputation: 2031

The arguments in split will be recycled if also x has multiple arguments:

strsplit(x = c("Whatever will be will be","Whatever will be will be"), 
         split = c("ever", "be"))
[[1]]
[1] "What"             " will be will be"

[[2]]
[1] "Whatever will " " will " 

The behaviour I suspect you expect is achieved with a |:

strsplit(x = "Whatever will be will be", split = c("ever|be"))
[[1]]
[1] "What"   " will " " will "

Upvotes: 2

Related Questions