str_replace_all replacing named vector elements iteratively not all at once

后端 未结 4 2058
误落风尘
误落风尘 2021-01-18 09:15

Let\'s say I have a long character string: pneumonoultramicroscopicsilicovolcanoconiosis. I\'d like to use stringr::str_replace_all to replace certain letters w

4条回答
  •  误落风尘
    2021-01-18 09:35

    My workaround would be to take advantage of the fact that str_replace_all can take functions as an input for the replacement.

    library(stringr)
    text_string = "developer"
    pattern <- "p|e"
    fun <- function(query) {
        if(query == "e") y <- "p"
        if(query == "p") y <- "e"
        return(y)
    }
    
    str_replace_all(text_string, pattern, fun)
    

    Of course, if you need to scale up, I would suggest to use a more sophisticated function.

提交回复
热议问题