Split character by multiple criteria in R

Viewed 212

I have a vector like that:

c("variable1+variable2 + variable3*variable4+ variable5")

I would like to split his string in a vector like:

c("variable1", "variable2", "variable3", "variable4", "variable5")

IMPORTANT 1: note that there are two kind of separators; + and *. IMPORTANT 2: note that sometimes there are a blank space between the word I wanna get and the separator, and other times there are not blank spaces.

3 Answers

In base R, we can use strsplit

out <- strsplit("variable1+variable2 + variable3*variable4+ variable5", 
          "\\s*[*+]\\s*")[[1]]

-output

out
[1] "variable1" "variable2" "variable3" "variable4" "variable5"

The structure is

dput(out)
c("variable1", "variable2", "variable3", "variable4", "variable5"
)

You can use stringr package with

library(stringr)
a <- c("variable1+variable2 + variable3*variable4+ variable5")

str_split(str_squish((str_replace_all(a, regex("\\W+"), " "))), " ")

Output:

[1] "variable1" "variable2" "variable3" "variable4" "variable5"

Another base R option using strsplit + trimws

> s <- c("variable1+variable2 + variable3*variable4+ variable5")

> trimws(unlist(strsplit(s, "\\*|\\+", perl = TRUE)))
[1] "variable1" "variable2" "variable3" "variable4" "variable5"
Related