Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

apply attributes to individual vector elements before mapping #1105

Closed
mkoohafkan opened this issue Oct 27, 2023 · 1 comment
Closed

apply attributes to individual vector elements before mapping #1105

mkoohafkan opened this issue Oct 27, 2023 · 1 comment

Comments

@mkoohafkan
Copy link

mkoohafkan commented Oct 27, 2023

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 mkoohafkan changed the title apply attributes to map elements apply overall attributes to vector elements before mapping Oct 27, 2023
@mkoohafkan mkoohafkan changed the title apply overall attributes to vector elements before mapping apply attributes to individual vector elements before mapping Oct 27, 2023
@mkoohafkan
Copy link
Author

Closing as the behavior is controlled by the [[ method definition. See tidyverse/stringr#529

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant