Split text based on dot in R

Antoine picture Antoine · Mar 18, 2015 · Viewed 18k times · Source

I have:

"word1.word2"

and I want:

"word1" "word2"

I know I have to use strsplit with perl=TRUE, but I can't find the regular expression for a period (to feed to the split argument).

Answer

A5C1D2H2I1M1N2O1R2T1 picture A5C1D2H2I1M1N2O1R2T1 · Mar 19, 2015

There are several ways to do this, both with base R and with the common string processing packages (like "stringr" and "stringi").

Here are a few in base R:

str1 <- "word1.word2"

strsplit(str1, ".", fixed = TRUE)  ## Add fixed = TRUE
strsplit(str1, "[.]")              ## Make use of character classes
strsplit(str1, "\\.")              ## Escape special characters