showkey
showkey

Reputation: 300

how can i get right result at the seperator of "|"?

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

Answers (3)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

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

Sven Hohenstein
Sven Hohenstein

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

Julien Navarre
Julien Navarre

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

Related Questions