Reputation: 920
I wanted to split a string with "+" separated one and used strsplit
as below but it doesn't work.
Here is the example
strsplit("aa + bb + cc", split = "+")
It shows character splitted one like this. Why doesn't it work?
[1] "a" "a" " " "+" " " "b" "b" " " "+" " " "c" "c"
How can I get this?
c("aa", "bb","cc")
Upvotes: 1
Views: 369
Reputation: 887068
An option with scan
from base R
scan(text = "aa + bb + cc", what = "", sep= "+", strip.white = TRUE, quiet = TRUE)
#[1] "aa" "bb" "cc"
Upvotes: 1
Reputation: 1364
Or you can try this way
library(stringr)
str_split("aa + bb + cc","[\\s\\+]+")
#[1] "aa" "bb" "cc"
Upvotes: 1
Reputation: 521093
I would use:
strsplit("aa + bb + cc", "\\s*\\+\\s*")[[1]]
[1] "aa" "bb" "cc"
The +
symbol is a regex metacharacter, and so needs to be escaped. If you also want to isolate the terms being added, then add optional whitespace on either side of the +
.
Upvotes: 1