user3069326
user3069326

Reputation: 575

grep function in R

I have a vector called ew12 which looks like this

2|7;27;0.878,0.888;

I seperated it using the scan command and ; as sep. What I then get is

ew12
[1] "2|7"      "27"       "0.878,0.888"    

I then want to grep the "2|7" pattern and use

grep("^2|7$", ew12) 

which results in [1] 1 2 3

but the pattern is not present in all three elements..

Thanks

Upvotes: 0

Views: 438

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81743

If you want to match the exact string, you have to use double escapes for the bar, i.e., \\|:

grep("^2\\|7$", ew12)
[1] 1

You can also use

which(ew12 == "2|7")
[1] 1

Upvotes: 2

PKumar
PKumar

Reputation: 11128

I think you are missing the parenthesis(If i am getting your question correctly).

Try : grep("^(2|7)$",ew12)

Upvotes: 1

Related Questions