user3354212 - 2 months ago 9

R Question

I have a vector:

`lst <- c("2,1","7,10","11,0","7,0","10,0","1,1","1,0","4,0","4,1","0,1","6,0")`

each element contains two numbers,separated by ",". I would like to get indexes of elements containing "1".

So the index list is expected:

`1, 6, 7, 9, 10`

Answer

`grep()`

will work nicely for this. By default, it returns the indices of the matched pattern.

```
grep("^1,|,1$", lst)
# [1] 1 6 7 9 10
```

The regular expression `^1,|,1$`

looks to match a string that

`^1,`

= starts with`1,`

`|`

OR`,1$`

= ends with`,1`