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.
If the purpose of this exercise is to show how to pass an argument to str_count from within reduce then you could do this:
reduce(sentences, function(x, y, p) x + str_count(y, p), p = "This", .init = 0)
#> [1] 3
Although I think the existing suggestions in the comments are a more readable way to achieve the same result. A simpler way to show how to pass an additional argument is to use something like the str_c function which takes strings as an argument and returns a string as a result.
reduce(sentences, str_c, sep = "___")
#> [1] "This is a sentence.___This is another sentence.___One more This"
reduce(sentences, str_c, sep = "___") %>% str_count("This")
#> [1] 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With