I dont know how to do this for loop with purrr

Hi all. My topic is related to my inability to perform the following for loop with the purrr package.

I have this vector

vctr <- c("caacute;mara", "capitaacute;n", "intreacute;pido")

and I need this result

c("cámara", "capitán", "intrépido")

I find the function str_replace_all and apply it with a for loop

args_1 <- list('aacute;', 'eacute;', 'iacute;')
args_2 <- list('á','é', 'í')

str_repare <- function(vctr, args_1, args_2){
  for(i in seq_along(arg_1)){
    vctr <- str_replace_all(vctr, args_1[[i]], args_2[[i]])
  }  
  return(vctr)
}

Surely there is a elegant and smarter way to do it with the purrr package but I could never do it on my own.

1 Like

One way to solve this problem is to instead create one function that would apply modification one after another with something like this:

library(magrittr)

vctr <- c("caacute;mara", "capitaacute;n", "intreacute;pido")
desired <-  c("cámara", "capitán", "intrépido")

args_1 <- c('aacute;', 'eacute;', 'iacute;')
args_2 <- c('á','é', 'í')

modifier <- purrr::map2(args_1, args_2, ~purrr::partial(stringr::str_replace_all, pattern = .x, replacement = .y)) %>%
  purrr::reduce(purrr::compose)

res <- purrr::map_chr(vctr, modifier)

all.equal(res, desired)
#> [1] TRUE

Created on 2019-02-02 by the reprex package (v0.2.1)
All it does is creating a function called modifier that is a composition of three modifications defined with args_1 and args_2. You then map it over your vector to get the result you want.

You could also use a named vector instead of a list and forget about purrr

library(stringr)
vctr <- c("caacute;mara", "capitaacute;n", "intreacute;pido")
args <- c('aacute;' = 'á', 'eacute;' = 'é', 'iacute;' = 'í')

str_replace_all(vctr, args)
#> [1] "cámara"    "capitán"   "intrépido"

Created on 2019-02-02 by the reprex package (v0.2.1)

6 Likes

That worked perfect, so my ignorance was in the stringr package rather than in purrr. Thank you so much.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.