rqdap

How to switch smoothly from qdap::mgsub() to textclean::mgsub()?


Due to R release issues I need to switch between qdap::mgsub() and textclean::mgsub(). The functions are almost the same, except for the order of the arguments:

qdap::mgsub(pattern,replacement,x)
textclean::mgsub(x,pattern,replacement)

I have a lot of code where I use qdap::mgsub(). Unfortenately I don't name the arguments properly when I pass them to function. So I need to reorder all of them in order to be able to use textclean::mgsub().

Is there (programmatically) an elegant way to switch between these two functions without having to change the order of the arguments?


Solution

  • You can use a regular expression to replace the occurrences in the text of every file you call the old function in, using a function like the following:

    replace_mgsub <- function(path) {
        file_text <- readr::read_file(path)
        file_text <- gsub("qdap::mgsub\\(([^, ]+) *, *([^, ]+) *, *([^\\)]) *\\)",
                          "textclean::mgsub\\(\\3, \\1, \\2\\)", file_text)
        readr::write_file(file_text, path)
    }
    

    which you would then call on every relevant path (I assume here you know the list of files you need to call the function on; if not, comment below and I can add some stuff on that). Here's a demo of the gsub() part of the function:

    file_text <- "qdap::mgsub(pattern,replacement,x)"
    cat(gsub("qdap::mgsub\\(([^, ]+) *, *([^, ]+) *, *([^\\)]) *\\)",
             "textclean::mgsub\\(\\3, \\1, \\2\\)", file_text))
    #> textclean::mgsub(x, pattern, replacement)
    file_text <- "# I'll have in this part some irrelevant code
    # to show it won't interfere with that
    y = rnorm(1000)
    qdap::mgsub(pattern,replacement,x)
    z = rnorm(10)
    # And also demonstrate multiple occurrences of the function
    # as well as illustrate that it doesn't matter if you have spaces
    # between comma separated arguments
    qdap::mgsub(pattern, replacement, x)"
    cat(gsub("qdap::mgsub\\(([^, ]+) *, *([^, ]+) *, *([^\\)]) *\\)",
             "textclean::mgsub\\(\\3, \\1, \\2\\)", file_text))
    #> # I'll have in this part some irrelevant code
    #> # to show it won't interfere with that
    #> y = rnorm(1000)
    #> textclean::mgsub(x, pattern, replacement)
    #> z = rnorm(10)
    #> # And also demonstrate multiple occurrences of the function
    #> # as well as illustrate that it doesn't matter if you have spaces
    #> # between comma separated arguments
    #> textclean::mgsub(x, pattern, replacement)