tidyverse / purrr

A functional programming toolkit for R
https://purrr.tidyverse.org/
Other
1.27k stars 271 forks source link

apply attributes to individual vector elements before mapping #1105

Closed mkoohafkan closed 10 months ago

mkoohafkan commented 10 months ago

This is pretty simple to do but this could potentially be a nice helper function. When mapping over elements of a vector, the attributes are lost before the function is applied:

library(purrr)
library(stringr)

keywords = stringr::coll(c("FOO", "BAR", "BAZ"), ignore_case = TRUE)
words = c("fuzz", "foo", "boat", "baz")
# stringr_pattern class is lost before str_detect is applied
map_lgl(keywords, function(x) any(stringr::str_detect(words, x)))
#> FALSE FALSE FALSE

It might be nice to have a helper function that applies the attributes of the input to each element, e.g.

apply_attr = function(x) {
  lapply(x, function(xx) {
    mostattributes(xx) = attributes(x)
    xx
  })
}

map_lgl(apply_attr(keywords), function(x) any(stringr::str_detect(words, x)))
#> TRUE FALSE TRUE
mkoohafkan commented 10 months ago

Closing as the behavior is controlled by the [[ method definition. See https://github.com/tidyverse/stringr/issues/529