Reputation: 300
I want to split a string .
str <- "3 |6 | 9 | 12"
unlist(strsplit(str,split="|"))
[1] "3" " " "|" "6" " " "|" " " "9" " " "|" " " "1" "2"
How can I get the result "3 6 9 12"?
Upvotes: 0
Views: 61
Reputation: 193547
I would actually forego strsplit
and just use scan
for something like this....
> str <- "3 |6 | 9 | 12"
> str
[1] "3 |6 | 9 | 12"
> scan(text = str, sep = "|")
Read 4 items
[1] 3 6 9 12
Upvotes: 2
Reputation: 81693
If you want a vector with all four substrings, you can use:
str <- "3 |6 | 9 | 12"
strsplit(str, " *\\| *")[[1]]
# [1] "3" "6" "9" "12"
Here, " *"
means any number of whitespaces.
Note that |
means or in regular expressions. You have to use double escapes for literal interpretation, i.e., \\|
.
Upvotes: 1
Reputation: 7830
Use gsub
to replace '|' by "empty". (with "fixed = TRUE" so "|" is a string to be matched as is, and not the "|" used in regexp)
str <- "3 |6 | 9 | 12"
> gsub("|", "", str, fixed = TRUE)
[1] "3 6 9 12"
Upvotes: 0