Fr.
Fr.

Reputation: 2895

Replacing a for loop (that modifies an object) with a purrr function?

I'm working with a more complex version of this code, which includes a for loop.

At each step of the loop, the object text gets modified, based on two values in the regex data frame.

Is there a way to replace that modifying for loop with a call to purrr::walk2 or something like that?

library(tidyverse)

text <- "apple, orange, spinach"
regex <- tibble::tibble(
  find = c("[Aa]pples?", "[Oo]ranges?", "[Ss]pinach"),
  replace = c("fruit", "fruit", "vegetable")
)

# can this loop be replaced with purrr::walk2 or something like that?
for (i in 1:nrow(regex)) {
  text <- str_replace(text, regex$find[ i ], regex$replace[ i ])
}

# > text
# [1] "fruit, fruit, vegetable"

I have read this question: How to replace a modifying for loop by purrr -- but am unable to apply the solution here.

Upvotes: 1

Views: 187

Answers (2)

Ian Campbell
Ian Campbell

Reputation: 24878

Here's an approach with walk2:

library(purrr)
walk2(.x = regex$find, .y = regex$replace,
      .f = ~assign("text", str_replace(text, .x, .y), envir = globalenv()))
text
#[1] "fruit, fruit, vegetable"

I agree with @MartinGal, however, that an alternative approach is probably a better plan.

Upvotes: 3

Martin Gal
Martin Gal

Reputation: 16998

That's not what you asked for, but in this case I recommend

unique(str_replace_all(text, regex$find, regex$replace))

which returns

[1] "fruit, fruit, vegetable"

Upvotes: 1

Related Questions