Create an index by searching part of the text only

Asked

Viewed 36 times

-1

I would like to create an index by searching only part of the text.

x <- c(4, 1, 6, "ab", 2, 1, "aa")

which(x == "a")

In the vector above, for example, I would like the return to be

[1] 4 7

That is, return all lines that contain the letter "a", regardless of whether you have anything else, line or letters.

  • Welcome to Stackoverflow! Try grep("a", x) and grepl("a", x)

1 answer

4

As already indicated in the comments, grep and its variants serve for this:

grep("a", x)
#> [1] 4 7

The option value shows the values:

grep("a", x, value = TRUE)
#> [1] "ab" "aa"

Use grepl to return a logical vector. See the help for regular expressions (?regex) if you need more elaborate patterns.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.