What is the syntax in R for returning the number of words matched in regular expression?

Viewed 72

R Package: stringr::words

I want to know the number of words that are exactly three letters long in the stringr::words file after applying the following regular expression:

x <- str_view(words, "^...$", match = TRUE)

While the code was able to extract words that are exactly three letters long, it does not tell me how many words there are. So, I thought the length function will be appropriate to find the number.

length(x)

The code returns 8, which cannot be as it is very clear that x is more than 8.

What is the proper syntax to calculate the number of words after matching with the regular expression, in this case, x?

Also, can anyone explain to me why length(x) returns 8 in the above example?

Thank you in advance.

3 Answers

str_view returns an HTML object which is used for viewing.

x <- str_view(words, "^...$", match = TRUE)
class(x)
#[1] "str_view"   "htmlwidget"

The 8 components that you see are

names(x)
#[1] "x"             "width"         "height"        "sizingPolicy"  "dependencies" 
#[6] "elementId"     "preRenderHook" "jsHooks"    

Instead of str_view use str_subset :

library(stringr)

x <- str_subset(words, "^...$")
x

#  [1] "act" "add" "age" "ago" "air" "all" "and" "any" "arm" "art" "ask" "bad" "bag"
# [14] "bar" "bed" "bet" "big" "bit" "box" "boy" "bus" "but" "buy" "can" "car" "cat"
# [27] "cup" "cut" "dad" "day" "die" "dog" "dry" "due" "eat" "egg" "end" "eye" "far"
# [40] "few" "fit" "fly" "for" "fun" "gas" "get" "god" "guy" "hit" "hot" "how" "job"
# [53] "key" "kid" "lad" "law" "lay" "leg" "let" "lie" "lot" "low" "man" "may" "mrs"
# [66] "new" "non" "not" "now" "odd" "off" "old" "one" "out" "own" "pay" "per" "put"
# [79] "red" "rid" "run" "say" "see" "set" "sex" "she" "sir" "sit" "six" "son" "sun"
# [92] "tax" "tea" "ten" "the" "tie" "too" "top" "try" "two" "use" "war" "way" "wee"
#[105] "who" "why" "win" "yes" "yet" "you"


length(x)
#[1] 110

Another option is str_count:

library(stringr)
sum(str_count(x, "^...$"))
[1] 3

Data:

x <- c("abc", "abcd", "ab", "abc", "abcsd", "edf")

I'd suggest using grep with length:

length(grep("^.{3}$", words))
# => [1] 110

With grep, you actually get a subset of the words and length will return the count of the found matches.

stringr::str_view can be used to view HTML rendering of regular expression match, and it does not actually return the list of matches. Beside grep, you may use stringr::str_subset.

Related