Consider this simple example which accumulates the occurrences of the word "This" from a string vector:
library(purrr)
library(stringr)
sentences <- c("This is a sentence.",
"This is another sentence.",
"One more This")
reduce(str_count(sentences, "This"), `+`) # SUCCESS! Returns 3
I'm trying to understand how to write this with sentences passed to reduce -- my failed attempts:
reduce(sentences, str_count, pattern = "This") # FAILS! unused argument (.x[[i]])
reduce(sentences, ~ str_count, pattern = "This") # FAILS! Returns signature for str_count()
reduce(sentences, ~ str_count(pattern = "This")) # FAILS! Argument "string" missing with no default.
reduce(sentences, ~ str_count("This")) # FAILS! Returns wrong result, 4.
reduce(sentences, ~ str_count(.x, pattern = "This") + str_count(.y, pattern = "This")) # FAILS! Returns wrong result, 1.
EDIT: For more clarity, consider a Python approach:
reduce(lambda a, x: a + x.count("This"), sentences, 0)
I'd be interested in a similar R approach, but I'm not sure if this is possible (?) because .count is a method in Python.