How to flag missing left-hand collocates with NA

Viewed 33

I want to compute collocates of the lemma GO, including all its forms such as go, goes, gone, etc.:

go <- c("go after it", "here we go", "he went bust", "go get it go", "i 'm gon na go", "she 's going berserk")

The lemma forms are stored in this vector:

lemma_GO <- c("go", "goes", "going", "gone", "went", "gon na")

and this vector turns them into an alternation pattern:

pattern_GO <- paste0("\\b(", paste0(lemma_GO, collapse = "|"), ")\\b")

However, when using the pattern with str_extract_all to extract the immediately left-hand collocate of GO, the extraction misses out on those strings where GO is the first word in the string and reoccurs later in the string:

library(stringr)
str_extract_all(go, paste0("'?\\b[a-z']+\\b(?=\\s?", pattern_GO, ")"))
[[1]]
character(0)

[[2]]
[1] "we"

[[3]]
[1] "he"

[[4]]
[1] "it"

[[5]]
[1] "'m" "na"

[[6]]
[1] "'s"

The expected result is this:

[[1]]
[1] NA

[[2]]
[1] "we"

[[3]]
[1] "he"

[[4]]
[1]  NA  "it"

[[5]]
[1] "'m" "na"

[[6]]
[1] "'s"

How can the extraction be mended to also return NA in the absence of a left-hand collocate?

1 Answers

You can add an alternative to match at the start of a string, or your consuming pattern:

str_extract_all(go, paste0("('?\\b[a-z']+\\b|^)(?=\\s?", pattern_GO, ")"))

See the regex demo.

See the R demo:

go <- c("go after it", "here we go", "he went bust", "go get it go", "i 'm gon na go", "she 's going berserk")
lemma_GO <- c("go", "goes", "going", "gone", "went", "gon na")
pattern_GO <- paste0("\\b(", paste0(lemma_GO, collapse = "|"), ")\\b")
library(stringr)
str_extract_all(go, paste0("('?\\b[a-z']+\\b|^)(?=\\s?", pattern_GO, ")"))

Output:

[[1]]
[1] ""

[[2]]
[1] "we"

[[3]]
[1] "he"

[[4]]
[1] ""   "it"

[[5]]
[1] "'m" "na"

[[6]]
[1] "'s"


Sukces #stdin #stdout 0.26s 42528KB
[1] "\\b(go|goes|going|gone|went|gon na)\\b"
[[1]]
[1] ""

[[2]]
[1] "we"

[[3]]
[1] "he"

[[4]]
[1] ""   "it"

[[5]]
[1] "'m" "na"

[[6]]
[1] "'s"

If you want, you can turn all empty items into NA using

res <- str_extract_all(go, paste0("('?\\b[a-z']+\\b|^)(?=\\s?", pattern_GO, ")"))
res <- lapply(res, function(x) ifelse(x=="", NA, x))
Related