Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a character string by the symbol "*"

Tags:

string

split

r

> test = "23*45"

I'd like to split testby the symbol *

I tried...

> strsplit(test,'*')

and I got...

[[1]]
[1] "2" "3" "*" "4" "5"

What I aim to have is:

[[1]]
[1] "23" "45"
like image 392
Remi.b Avatar asked Jun 25 '26 12:06

Remi.b


1 Answers

You need to escape the star...

test = "23*45"

strsplit( test , "\\*" )
#[[1]]
#[1] "23" "45"

The split is a regular expression and * means the preceeding item is matched zero or more times. You are splitting on nothing , i.e. splitting into individual characters, as noted in the Details section of strsplit(). \\* means *treat * as a literal *.

Alternatively use the fixed argument...

strsplit( test , "*" , fixed = TRUE )
#[[1]]
#[1] "23" "45"

Which gets R to treat the split pattern as literal and not a regular expression.

like image 158
Simon O'Hanlon Avatar answered Jun 28 '26 03:06

Simon O'Hanlon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!