r - Select element with specific character -
i have atomic vector character different length each elements belows:
<- c("abcde", "adlbb", "asdlb", "abcdg", "abcdgdl") my task select "dl".
the tricky part dl not fixed specific position of elements.
my ideal answer is:
[1] "adlbb" "asdlb" "abcdgdl" i tried grep("[dl]", a, value=true) seems not working.
thanks.
with grep be
> <- c("abcde", "adlbb", "asdlb", "abcdg", "abcdgdl") > grep("dl", a, value = true, fixed = true) ## [1] "adlbb" "asdlb" "abcdgdl" no need [ capture characters if set fixed = true. capture "dl" is. variety
> a[grep("dl", a, fixed = true)] ## [1] "adlbb" "asdlb" "abcdgdl" since mentioned you're learning regular expressions in r, here other variations of grep make handy in many situations.
alone, returns indices of captured regex
> grep("dl", a, fixed = true) ## [1] 2 3 5 when add invert = true, indices of vector did not match (essentially opposite of above line)
> grep("dl", a, fixed = true, invert = true) ## [1] 1 4 adding value = true that, values did not match. again, opposite.
> grep("dl", a, fixed = true, invert = true, value = true) ## [1] "abcde" "abcdg" if add elements lower case letters mixed in, can capture ignore.case. no longer want fixed because we're searching variations in cases.
> b <- c(a, "abcdle", "dlabrt", "abcde") > grep("dl", b, value = true, ignore.case = true) ## [1] "adlbb" "asdlb" "abcdgdl" "abcdle" "dlabrt" these arguments allow user cut down on lengthy regular expressions.
Comments
Post a Comment