Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the strsplit function with a period

Tags:

r

strsplit

I would like to split the following string by its periods. I tried strsplit() with "." in the split argument, but did not get the result I want.

s <- "I.want.to.split" strsplit(s, ".") [[1]]  [1] "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" 

The output I want is to split s into 4 elements in a list, as follows.

[[1]] [1] "I"     "want"  "to"    "split" 

What should I do?

like image 422
user3022875 Avatar asked Oct 30 '14 23:10

user3022875


People also ask

What is the code used to break apart a string using the Strsplit () function?

Strsplit() Function SyntaxStrsplit(): An R Language function which is used to split the strings into substrings with split arguments. Where: X = input data file, vector or a stings. Split = Splits the strings into required formats.

How does Strsplit work in R?

strsplit() Function in R. The strsplit() in R programming language function is used to split the elements of the specified character vector into substrings according to the given substring taken as its parameter.


1 Answers

When using a regular expression in the split argument of strsplit(), you've got to escape the . with \\., or use a charclass [.]. Otherwise you use . as its special character meaning, "any single character".

s <- "I.want.to.split" strsplit(s, "[.]") # [[1]] # [1] "I"     "want"  "to"    "split" 

But the more efficient method here is to use the fixed argument in strsplit(). Using this argument will bypass the regex engine and search for an exact match of ".".

strsplit(s, ".", fixed = TRUE) # [[1]] # [1] "I"     "want"  "to"    "split" 

And of course, you can see help(strsplit) for more.

like image 54
Rich Scriven Avatar answered Sep 22 '22 14:09

Rich Scriven